如何在C#中引用实际类而不是基类中的枚举

时间:2018-09-04 13:23:20

标签: c# inheritance enums abstract-class

我对此很麻烦,因为我也很难正确地制定它。使其难以谷歌。我将尽力解释清楚。我简化了代码,以使问题更清楚

我有一个抽象类,该抽象类的方法和属性被所有以此为基类的类所使用:

public abstract class TheBaseClass{

    //some properties here

    public enum MyEnum{} // this one every class has. It is pretty much empty here. Not sure if this is best practice.

    //some methods here
}

然后有许多基于此的类:

public SpecializedClass : TheBaseClass{

    //some more properties here

    public new enum MyEnum{} //every single class has a different enum

    //some more methods here
}

现在,在代码的其他地方,我有一个方法

public void MyMethod(TheBaseClass baseclassobject){

    //do stuff
    var usedforsomething = ((TheBaseClass.MyEnum)i).ToString() //i being an int. This is used to name something in a plot.
    //do more stuff
}

使用TheBaseClass作为方法的参数的原因是,在我编写很长的代码之前,我对从TheBaseClass派生的每个类都做了mymethod的工作。拥有重复的代码不是很好,所以我改用了此方法,并想使用参数SpecializedClass(以及许多其他类似的类)来调用它。问题是,当调用TheBaseClass.MyEnum时,我自然会获得BaseClass的枚举,而不是SpecializedClass的枚举。我一直在尝试如何在方法中获取正确的枚举,而不管我给它什么基类对象,但似乎找不到解决方法。

如何获得基本类对象的枚举?我尝试了一些不同的操作,但似乎没有用。 我认为的问题是,枚举不是我可以从对象中调用的属性或方法,而是需要调用ClassName.MyEnum,而该方法中没有className。

一种解决方案是为每个类类型创建一个方法,以该特定类类型为参数,但这似乎有很多重复的代码。

例如,如果我有50个不同的派生类,例如SpecializedClass

2 个答案:

答案 0 :(得分:4)

我认为反思是您唯一的选择。

var usedforsomething = 
      baseclassobject
       .GetType()
       .GetNestedType(nameof(TheBaseClass.MyEnum))
       .GetEnumName(i);

但是也许更好的解决方案是在您的子类必须重写的基类中添加抽象函数GetName

public abstract class TheBaseClass
{

    public enum MyEnum {a,b }

    public abstract string GetName(int value);
}

public class SpecializedClass : TheBaseClass
{

    public new enum MyEnum {c,d }

    public override string GetName(int value)
    {
        return ((MyEnum)value).ToString();
    }
}

您可以做到:

var usedforsomething = baseclassobject.GetName(i);

您可以避免反射,也可以避免依赖于使用特定名称MyEnum声明枚举的子类。

答案 1 :(得分:-1)

我可能对您的理解不正确,但是您是否尝试在MyMethod中做一些反射操作以采用必要的枚举类型:

public static void MyMethod(TheBaseClass baseclassobject)
{
    Type enumType = baseclassobject.GetType().GetNestedType("MyEnum");
    var usedforsomething = Enum.GetName(enumType, 1);
    Console.WriteLine(usedforsomething);
}