簡體   English   中英

class作為具有反射C#的另一個類的屬性

[英]class as a property of another class with reflection C#

看下面的代碼,有人可以幫助我....

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

獲取未找到屬性的錯誤。

默認情況下,類成員是private的。 使您的屬性public ,它應該工作。 另外,刪除屬性字符串上的額外空格: "Pdetails"

您的屬性名稱中有一個額外的空格字符。 "Pdetails ""Pdetails"

Pdetails屬性不public ,所以你的BindingFlags應該是

BindingFlags.NonPublic | BindingFlags.Instance

另外,請參閱Joel Etherton的回答。

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

您只能將字符串格式的對象類型傳遞給asm.GetType函數。 另一個是你在哪里聲明了asm對象。 如果你沒有,那么先定義它。

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

感謝您的支持我使用高級代碼來解決我的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM