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

问题描述 投票:5回答:2

我遇到了麻烦,因为我也很难正确地制定它。谷歌更难以谷歌。我将尝试尽可能清楚地解释。我简化了代码,使我的问题更加清晰

我有一个抽象类,其中包含所有以此为基类的clases使用的方法和属性:

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作为方法的参数的原因是,在我有很长的代码之前,我做了mymethod对从TheBaseClass派生的每个类所做的事情。有重复的代码是不好的,所以我改为使用参数SpecializedClass(还有许多其他类)来创建这个方法。问题是当调用TheBaseClass.MyEnum时,我自然得到BaseClass的枚举,而不是来自SpecializedClass的枚举。我一直在尝试如何在方法中获得正确的枚举,无论我给它什么baseclassobject,但似乎无法找到解决方案。

我怎样才能得到任何类baseclassobject的枚举?我尝试了一些不同的东西,但似乎没有用。我认为问题是enum不是我可以从对象调用的属性或方法,而是需要调用ClassName.MyEnum,我在方法中没有className。

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

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

c# inheritance enums abstract-class
2个回答
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
投票

我可能不正确地理解你,但你是否尝试在MyMethod做一些反思的东西来采取必要的枚举类型:

public static void MyMethod(TheBaseClass baseclassobject)
{
    Type enumType = baseclassobject.GetType().GetNestedType("MyEnum");
    var usedforsomething = Enum.GetName(enumType, 1);
    Console.WriteLine(usedforsomething);
}
© www.soinside.com 2019 - 2024. All rights reserved.