class作为具有反射C#的另一个类的属性

时间:2012-07-18 12:11:50

标签: c# .net reflection properties

见下面的代码,有人可以帮助我......

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);
    }
}

找不到属性的错误。

5 个答案:

答案 0 :(得分:3)

默认情况下,班级成员为private。设置您的属性public,它应该有效。另外,删除属性字符串上的额外空格:"Pdetails"

答案 1 :(得分:3)

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

答案 2 :(得分:3)

属性Pdetails不是public,因此您的BindingFlags应为

BindingFlags.NonPublic | BindingFlags.Instance

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

答案 3 :(得分:0)

Type type = asm.GetType("person");

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

答案 4 :(得分:0)

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);
        }

感谢您的支持我使用高级代码来解决我的问题。