开发者

Can i use a generic implicit or explicit operator? C#

How do i change the following statement so it accepts any type instead of long? Now here is the catch, if there is no constructor i dont want it compiling. So if theres a constructor for string, long and double but no bool how do i have this one line work for all of these support types?

ATM i just copied pasted it b开发者_运维知识库ut i wouldnt like doing that if i had 20types (as trivial as the task may be)

public static explicit operator MyClass(long v) { return new MyClass(v); }


Now I can tell you that the answer to you question is "No, we can't" because:

User-defined conversion must convert to or from the enclosing type.

That's why we can't use generic types here.

public class Order
{
    public string Vender { get; set; }
    public decimal Amount { get; set; }
}

public class AnotherOrder
{
    public string Vender { get; set; }
    public decimal Amount { get; set; }
    public static explicit operator AnotherOrder(Order o)
    {
        //this method can be put in Order or AnotherOrder only
    }
}


Maybe it works:

public static explicit operator MyClass<T>(T t) where T:new()
{ 
  return new MyClass(t);
}

EDIT

I checked your request just now and found sth weird. "So if theres a constructor for string, long and double but no bool" Can you tell me why you want to do this.

EDIT

I tried on my machine, it seems that generic types can't be used in explicit methods. Maybe we can only go back to an object parameter?


Use Object type, if I'm not mistaken.

public static explicit operator MyClass(object v) { return new MyClass(v); }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜