[英]How to pass a generic enum to a method and set it to a dynamic object inside the method
我有大约 20 多个相同的枚举,但来自不同的 Web 服务库,因此在使用它们时,它们都需要完全命名空间引用,如下所示
每个枚举如下所示
public enum yesnounspecified
{
unspecified,
yes,
no,
}
在我的方法中,我设置了动态对象的所有值,也来自每个不同的 Web 服务,我需要能够将枚举设置为 (yes/no) 但不确定如何传入并使用它
ex.
MyMethod("something", new WebServices_Production_TrustOnline_ARM.objectToFill());
public void MyMethod(string otherParam, dynamic someObject) {
// 'cigarettes' is a 'yesnospecified' enum
someObject.cigarettes = // need to set the enum value (yes/no) here but not sure how to pass it in and set it
}
使用反射
public void MyMethod(string otherParam, object someObject)
{
var prop = someObject.GetType().GetProperty("cigarettes");
var enumType = prop.PropertyType;
prop.SetValue(someObject, Enum.Parse(enumType, "yes"), null);
}
这使用反射获取有关“香烟”属性的信息,包括枚举类型。 然后可以使用Enum.Parse(enumType, string)
或Enum.ToObject(enumType, intValue)
来构造这种类型的值。 SetValue
将构造的值写入属性。
使用泛型
另一种选择 - 如果该值是固定的 - 将使该方法通用并将枚举值传递给该方法:
public void MyMethod<T>(string otherParam, dynamic someObject, T value)
{
someObject.cigarettes = value;
}
调用: MyMethod("x", obj, yesnounspecified.yes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.