[英]Generic enum as method parameter
Given a constructor 给定一个构造函数
public MyObject(int id){
ID = id;
}
And two enums: 两个枚举:
public enum MyEnum1{
Something = 1,
Anotherthing = 2
}
public enum MyEnum2{
Dodo = 1,
Moustache= 2
}
Is it possible to pass in a generic enum as a parameter of the constructor? 是否可以传入通用枚举作为构造函数的参数? I'm looking for a solution along the lines of:
我正在寻找一个解决方案:
public MyObject(enum someEnum){
ID = (int)someEnum;
}
So you can do: 所以你可以这样做:
var newObject = new MyObject(MyEnum1.Something);
var anotherObject = new MyObject(MyEnum2.Dodo);
Another option would be: 另一种选择是:
public MyObject(Enum someEnum){
ID = Convert.ToInt32(someEnum);
}
This way you can use it like you requested without having to cast to int
each time you call your contstructors: 通过这种方式,您可以按照自己的要求使用它,而无需在每次调用contstructors时转换为
int
:
var newObject = new MyObject(MyEnum1.Something);
var anotherObject = new MyObject(MyEnum2.Dodo);
Why do you want to pass the enums, while you could pass integers ? 为什么你想传递枚举,而你可以传递整数?
var newObject = new MyObject((int)MyEnum1.Something);
var anotherObject = new MyObject((int)MyEnum2.Dodo);
and use your first constructor : 并使用您的第一个构造函数:
public MyObject(int id){
ID = id;
}
Just use a generic constructor: 只需使用通用构造函数:
class MyObject<T> {
public MyObject(T someEnum) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new ArgumentException("Not an enum");
ID = Convert.ToInt32(someEnum);
}
}
Now you can easily call it like this: 现在你可以像这样轻松调用它:
var m = new MyObject<MyEnum>(MyEnum1.Something);
But easier would be to pass the enum as integer to the constructor as mentioned in other answers. 但更容易将枚举作为整数传递给构造函数,如其他答案中所述。
Well, if you really need to make this call generic for a wide variety of types, then IMHO you should use: 好吧,如果你真的需要使这个调用泛型为各种类型,那么恕我直言你应该使用:
Enum
; Enum
; Int32
); Int32
); Now cast your object. 现在投射你的物体。
public static Int32 GetAnInt<T>(T arg) where T : struct { if ((typeof(T).IsEnum)) { var underlyingType = typeof(T).GetEnumUnderlyingType(); if (underlyingType == typeof(Int32) || underlyingType == typeof(Int16)) //etc. { try { dynamic value = arg; var result = (Int32)value; // can throw InvalidCast! return result; } catch { throw; } } else { throw new InvalidCastException("Underlying type is certainly not castable to Int32!"); } } else { throw new InvalidCastException("Not an Enum!"); } }
That way you achieve the beautiful syntax of: var j = GetAnInt(MyEnum.FirstValue);
这样你就可以实现漂亮的语法:
var j = GetAnInt(MyEnum.FirstValue);
Are you using properties enum or parameters. 您使用属性枚举或参数。
public enum Enum1{}
public Enum1 enum1 { get;set; }
public MyObject()
{
ID = (int)enum1;
}
Just try it. 就试一试吧。 I hope it is useful.
我希望它有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.