簡體   English   中英

在派生類型中找不到屬性集方法

[英]Property set method not found in a derived type

正如在.NET 反射設置私有屬性中討論的那樣,可以使用私有設置器設置屬性。 但是當在 class 基類中定義該屬性時,會拋出 System.ArgumentException:“找不到屬性設置方法”。

一個例子可以是:

using System;
class Test
{
    public DateTime ModifiedOn { get; private set;}
}

class Derived : Test
{
}

static class Program
{
    static void Main()
    {
        Derived p = new Derived ();
        typeof(Derived).GetProperty("ModifiedOn").SetValue(
            p, DateTime.Today, null);
        Console.WriteLine(p.ModifiedOn);
    }
}

有誰知道解決這種情況的方法?

編輯:給出的示例是問題的簡單說明。 在現實世界的場景中,我不知道該屬性是在基數 class 中定義的,還是在基數 class 的基數中定義的。

我有一個類似的問題,我的私有財產是在基數 class 中聲明的。我使用DeclaringType來獲取定義屬性的 class 的句柄。

using System;
class Test
{
    public DateTime ModifiedOn { get; private set;}
}

class Derived : Test
{
}

static class Program
{
    static void Main()
    {
        Derived p = new Derived ();

        PropertyInfo property = p.GetType().GetProperty("ModifiedOn");
        PropertyInfo goodProperty = property.DeclaringType.GetProperty("ModifiedOn");

        goodProperty.SetValue(p, DateTime.Today, null);

        Console.WriteLine(p.ModifiedOn);
    }
}

我認為這會起作用:

using System;
class Test
{
    public DateTime ModifiedOn { get; private set;}
}

class Derived : Test
{
}

static class Program
{
    static void Main()
    {
        Derived p = new Derived ();
        typeof(Test).GetProperty("ModifiedOn").SetValue(
            p, DateTime.Today, null);
        Console.WriteLine(p.ModifiedOn);
    }
}

您需要從 class 獲取屬性定義,它實際上是在派生的 class 上定義的

編輯:

要在任何基類 class 上選擇它,您需要在所有父類中查找它。

這樣的事情然后遞歸到基地 class 直到你打 object 或找到你的財產

typeof(Derived ).GetProperties().Contains(p=>p.Name == "whatever")

@LukeMcGregor 的另一種選擇是使用 BaseType

typeof(Derived)
    .BaseType.GetProperty("ModifiedOn")
    .SetValue(p, DateTime.Today, null);

我做了這個可重復使用的方法。 它處理我的場景。

    private static void SetPropertyValue(object parent, string propertyName, object value)
    {
        var inherType = parent.GetType();
        while (inherType != null)
        {
            PropertyInfo propToSet = inherType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
            if (propToSet != null && propToSet.CanWrite)
            {
                propToSet.SetValue(parent, value, null);
                break;
            }

            inherType = inherType.BaseType;
        }
    }

暫無
暫無

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

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