Ambiguous call between two C# extension generic methods one where T:class and other where T:struct

后端 未结 3 1621
小蘑菇
小蘑菇 2020-11-30 21:59

Consider two extension methods:

public static T MyExtension(this T o) where T:class
public static T MyExtension(this T o) where T:struct
         


        
3条回答
  •  独厮守ぢ
    2020-11-30 22:36

    Eric Lippert explains better than I ever could, here.

    I have come across this myself. My solution was

    public void DoSomthing (T theThing){
        if (typeof (T).IsValueType)
            DoSomthingWithStruct (theThing);
        else
            DoSomthingWithClass (theThing);  
    }
    
    // edit - seems I just lived with boxing
    
    public void DoSomthingWithStruct (object theThing)
    public void DoSomthingWithClass(object theThing)
    

提交回复
热议问题