【问题标题】:class as a property of another class with reflection C#类作为具有反射 C# 的另一个类的属性
【发布时间】:2012-07-17 11:18:26
【问题描述】:

请参阅下面的代码,有人可以帮助我....

public class person
{ 
  Public string name  { get; set; };  
  Public personDetails Pdetails { get; };
}

public class personDetails
{
  Public bool hasChild  { get; set; }
  Public string ChildName  { get; set; }
}


static void Main(string[] args)
{
    Type type = asm.GetType(person);

    object classInstance = Activator.CreateInstance(type); 


    PropertyInfo prop = type.GetProperty("Pdetails ", BindingFlags.Public | BindingFlags.Instance);

    if (null != prop && prop.CanWrite)
    {
        prop.SetValue(classInstance, null , null);
    }
}

获取未找到属性的错误。

【问题讨论】:

  • 将您的类型名称大写!另外,这个 string? 到底是什么?字符串一个引用类型。
  • 顺便说一句,你的外壳伤了我的眼睛!看看msdn.microsoft.com/en-us/library/ms229043.aspx 大写规则。
  • 你是在写这样的代码还是对 SO 来说太难看了? type.GetProperty("Pdetails " 属性名称不能包含空格。
  • 此代码无法编译,因为Type type = asm.GetType(person) 后面没有分号
  • 感谢重播,我尝试使用带有控制台应用程序的动态加载 dll。我的问题是如何设置类 personDetails 属性的成员

标签: c# .net reflection properties


【解决方案1】:

属性Pdetails 不是public,所以你的BindingFlags 应该是

BindingFlags.NonPublic | BindingFlags.Instance

另外,请参阅 Joel Etherton 的回答。

【讨论】:

  • 感谢重播,我尝试使用带有控制台应用程序的动态加载 dll。我的问题是如何设置类 personDetails 属性的成员
【解决方案2】:

类成员默认为private。将您的属性设为public,它应该可以工作。另外,删除属性字符串上的多余空格:"Pdetails"

【讨论】:

    【解决方案3】:

    您的属性名称中有一个额外的空格字符。 "Pdetails ""Pdetails" 不同。

    【讨论】:

      【解决方案4】:
      Type type = asm.GetType("person");
      

      您只能将字符串格式的对象类型传递给 asm.GetType 函数。 另一个是你在哪里声明了 asm 对象。如果你没有,那么先定义它。

      【讨论】:

        【解决方案5】:
        static object GetPropertyValue(object obj, string propertyName)
                {
                    var objType = obj.GetType();
                    var prop = objType.GetProperty(propertyName);
        
                    return prop.GetValue(obj, null);
                }
                static void SetPropertyValue(object obj, string propertyName, int values)
                {
                    var objType = obj.GetType();
                    var prop = objType.GetProperty(propertyName);
                    prop.SetValue(obj, values, null);
                }
        

        感谢您的支持,我已经使用上面的代码解决了我的问题。

        【讨论】:

          猜你喜欢
          • 2015-06-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-04
          • 2019-09-05
          • 2012-06-16
          • 2018-08-19
          • 1970-01-01
          相关资源
          最近更新 更多