[英]Cannot access inherited property if class has nested class of same name
我想访问我的一些 class 的属性,但得到编译器错误“CS0572 - 无法通过表达式引用类型”。
我有以下设置
public interface IHelper {
void DoHelp();
}
public abstract class ClassWithHelperBase<THelper> where THelper : IHelper {
public THelper Helper { get; }
}
public class ClassWithHelper : ClassWithHelperBase<ClassWithHelper.Helper> {
// use a nested class, since there will be n classes deriving from ClassWithHelper and giving each helper a readable name (in this example ClassWithHelperHelper) is ugly
public class Helper : IHelper {
public static void SomeStaticMethod() { }
public void DoHelp() { }
}
}
public class Test {
private ClassWithHelper myClass;
public void DoTest() {
((ClassWithHelperBase<ClassWithHelper.Helper>) myClass).Helper.DoHelp(); // this works, but is ugly
myClass.Helper.DoHelp(); // what I want, but it's not working
//myClass.Helper.SomeStaticMethod(); // funnily IDE supposes static methods here even though the resulting code is invalid, since I am (obviously) not referencing the class type
}
}
该界面对于复制是不必要的,为了清楚起见,我添加了它。
注意:我不想调用 static 方法,我只是添加了它,以显示 IDE 混淆了成员和 class 限定符。
有没有办法访问myClass
的属性Helper
,而无需强制转换myClass
或重命名嵌套的 class? 又名:为什么编译器不能区分成员和嵌套的 class?
问题是由于Helper
class (type) 和Helper
属性之间的名称冲突。 尝试这个
public interface IHelper
{
void DoHelp();
}
public abstract class ClassWithHelperBase<THelper> where THelper : IHelper
{
public THelper Helper { get; set; }
}
public class ClassWithHelper : ClassWithHelperBase<ClassWithHelper.CHelper>
{
// use a nested class, since there will be n classes deriving from ClassWithHelper and giving each helper a readable name (in this example ClassWithHelperHelper) is ugly
public class CHelper : IHelper
{
public static void SomeStaticMethod() {}
public void DoHelp() { }
}
}
public class Test
{
private ClassWithHelper myClass;
public void DoTest() {
myClass.Helper.DoHelp();
ClassWithHelper.CHelper.SomeStaticMethod();
}
}
在这里,我将Helper
class 重命名为CHelper
,因此编译器现在可以区分 class 和属性,因此myClass.Helper.DoHelp();
现在无需演员表即可工作。
如果“不重命名嵌套类”要求是绝对强制性的,那么也可以通过重命名基础 class 中的 Helper 属性以避免名称冲突来解决问题。 但是,我无法想象更好的物业名称。
不幸的是,对于 static 方法,您不能引用myClass
实例。 因此,您将需要引用整个类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.