首页 > 解决方案 > 如果类具有同名的嵌套类,则无法访问继承的属性

问题描述

我想访问我的某个类的属性,但得到编译器错误“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的情况下访问 的属性?阿卡:为什么编译器不能区分成员和嵌套类?myClassmyClass

标签: c#genericsinheritancepropertiesinner-classes

解决方案


问题是由于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();
    }
}

在这里,我将Helperclass 重命名为CHelper,因此编译器现在可以区分 class 和 property,因此该行myClass.Helper.DoHelp();现在可以在没有强制转换的情况下工作。

如果“不要重命名嵌套类”要求是绝对强制性的,那么也可以通过重命名基类中的 Helper 属性以避免名称冲突来解决问题。但是,我无法想象更好的物业名称。

不幸的是,对于静态方法,您不能引用myClass实例。因此,您将需要引用整个类型。


推荐阅读