Is there a constraint that restricts my generic method to numeric types?

后端 未结 21 2643
栀梦
栀梦 2020-11-21 05:48

Can anyone tell me if there is a way with generics to limit a generic type argument T to only:

  • Int16
  • Int32
21条回答
  •  再見小時候
    2020-11-21 06:37

    I would use a generic one which you could handle externaly...

    /// 
    /// Generic object copy of the same type
    /// 
    /// The type of object to copy
    /// The source object to copy
    public T CopyObject(T ObjectSource)
    {
        T NewObject = System.Activator.CreateInstance();
    
        foreach (PropertyInfo p in ObjectSource.GetType().GetProperties())
            NewObject.GetType().GetProperty(p.Name).SetValue(NewObject, p.GetValue(ObjectSource, null), null);
    
        return NewObject;
    }
    

提交回复
热议问题