c# - 如果类具有同名的嵌套类,则无法访问继承的属性
问题描述
我想访问我的某个类的属性,但得到编译器错误“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
解决方案
问题是由于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
class 重命名为CHelper
,因此编译器现在可以区分 class 和 property,因此该行myClass.Helper.DoHelp();
现在可以在没有强制转换的情况下工作。
如果“不要重命名嵌套类”要求是绝对强制性的,那么也可以通过重命名基类中的 Helper 属性以避免名称冲突来解决问题。但是,我无法想象更好的物业名称。
不幸的是,对于静态方法,您不能引用myClass
实例。因此,您将需要引用整个类型。
推荐阅读
- powershell - 验证本地机器证书
- hibernate - 一对一单向添加唯一约束
- sql - 如何从 URL 中提取某些级别的网址?
- c# - 我如何在这个例子中添加一个静态 Main() 方法?
- c# - 如何在 Android-Unity3D 应用程序中打开 PDF?
- c# - C# ASP.NET 在没有 JSON.NET 的情况下将 JSON 解析为数据集
- javascript - 我应该如何处理 React 组件库中的国际化?
- mysql - 在MySQL中设置变量等于列
- c# - 是否存在与 SQL 中的 LAG() 函数等效的实体的 linq?
- c# - 快捷键,特别是对话框 WPF 中的 alt 键