如何解决如果类具有同名的嵌套类,则无法访问继承的属性
我想访问我的某个类的属性,但收到编译器错误“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
}
}
界面对于复制来说是不必要的,为了清楚起见,我添加了它。
注意:我不想调用静态方法,我只是添加了它,以显示 IDE 混淆了成员和类限定符。
有没有办法访问 Helper
的属性 myClass
,而无需强制转换 myClass
或重命名嵌套类?
Aka:为什么编译器不能区分成员和嵌套类?
解决方法
问题是由于 Helper
类(类型)和 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
类重命名为 CHelper
,因此编译器现在可以区分类和属性,因此行 myClass.Helper.DoHelp();
现在无需强制转换即可工作。
如果“不要重命名嵌套类”的要求是绝对强制性的,那么也可以通过重命名基类中的 Helper 属性以避免名称冲突来解决问题。但是,我想不出更好的名称来命名该物业。
不幸的是,对于静态方法,您不能引用 myClass
实例。因此,您需要引用整个类型。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。