代码之家  ›  专栏  ›  技术社区  ›  chuckd

如何将泛型枚举传递给方法并将其设置为方法内的动态对象

  •  0
  • chuckd  · 技术社区  · 6 年前

    1. Web服务\u生产\u在线信任_ARM.YES未指定
    2. Web服务\u开发\u在线信任_ARM.YES未指定
    3. Web服务\u开发\u在线信任_BW.YES未指定
    4. 等高达20+

    其中每个枚举如下所示

    public enum yesnounspecified
    {
        unspecified,
        yes,
        no,
    }
    

    我需要能够将枚举设置为(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
    
    }
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Klaus Gütter    6 年前

    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);