gpt4 book ai didi

c# - 无法从基类获取具有私有(private) setter 的属性的 GetSetMethod

转载 作者:行者123 更新时间:2023-12-03 20:36:54 25 4
gpt4 key购买 nike

我无法使用私有(private) setter 从基类中获取属性的 GetSetMethod,当属性不是来自基类时它可以工作。

static void Main()
{
Console.WriteLine(typeof(Foo).GetProperty("Prop1").GetSetMethod(true));// this is null
Console.WriteLine(typeof(Foo).GetProperty("Prop2").GetSetMethod(true));// this has value
}

public class FooBase
{
public string Prop1 { get; private set; }
}

public class Foo : FooBase
{
public string Prop2 { get; private set; }
}

是否可以从基类获取或设置属性的值

最佳答案

当您将 setter 标记为 private 时,setter 方法的元数据在其派生类型中确实丢失了。您必须在其 DeclaringType 中找到它(它是 private 的类型)。

你可以试试这个:

var prop = typeof(Foo).GetProperty("Prop1");
var setter = prop.GetSetMethod(true);

if (setter == null)
setter = prop.DeclaringType.GetProperty(prop.Name).GetSetMethod(true);

关于c# - 无法从基类获取具有私有(private) setter 的属性的 GetSetMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31807874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com