gpt4 book ai didi

c# - 设置隐藏基类的属性

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:23 25 4
gpt4 key购买 nike

我有以下代码:

public class Ancestor
{
public string Property {get; protected set;}
}

public class Base : Ancestor
{
public string Property {get; set;}
}

public class Derived : Base
{
public Derived(string message)
{
//I need both properties to have the message value
}
}

Ancestor 和 Base 类不是我的代码,我无法更改它们。
有什么办法可以设置Ancestor的属性为message的值吗?
显然简单地做类似下面的事情是行不通的

Ancestor ancestor = this;
ancestor.Property = message

因为 setter 是 protected 。

最佳答案

仅通过反射:

 public class Derived : Base
{
public Derived(string message)
{
Type type = typeof(Ancestor);
Ancestor a = (Ancestor)this;
type.GetProperty("Property").SetMethod.Invoke(a, new[] { message });
}
}

关于c# - 设置隐藏基类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28169652/

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