从嵌套类访问外部类隐藏的基属性
本文关键字:隐藏 属性 外部 嵌套 访问 | 更新日期: 2023-09-27 18:20:41
假设我有一个类,它有一个隐藏其基属性的属性和一个嵌套类。是否可以从嵌套类访问基础hidden*virtual*属性?
这里有一个例子:
class BaseClass
{
protected virtual String SomeProperty {get; set;}
}
class Inherited : BaseClass
{
protected new String SomeProperty {get; set;}
class Nested
{
Inherited parent;
public Nested(Inherited parent)
{
this.parent = parent;
}
public void SomeMethod()
{
//How do I access the SomeProperty which belongs to the BaseClass?
}
}
}
我能想到的唯一解决方案是向Inherited类添加一个返回base.SomeProperty
的私有方法。有更好的解决方案吗?
您可以将InheritedClass
引用强制转换为BaseClass
。由于您隐藏了基本属性而不是覆盖它,所以这应该可以做到。
public void SomeMethod()
{
BaseClass baseRef = parent;
// do stuff with the base property:
baseRef.SomeProperty = someValue;
}
编辑:
为了实现这一点,嵌套类必须可以访问BaseClass
的SomeProperty
属性,方法是使其成为internal
(如果您不想使该属性在声明程序集之外可访问)或protected internal
(如果您想允许在其他程序集的派生类中重写)。
如果这两个选项都是禁止的(即,当派生类已经在另一个程序集中时),那么就无法声明包装器属性。
private string SomeBaseProperty
{
get
{
return base.SomeProperty;
}
set
{
base.SomeProperty = value;
}
}