我可以使用通用的隐式或显式运算符吗? C#
我如何更改以下语句,使其接受任何类型而不是长?现在这里是catch,如果没有构造函数,我不想编译它。因此,如果这是一个字符串的构造函数,long和double,但是没有bool,我如何让这一行支持所有这些支持类型?
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我刚刚复制粘贴它但我不想这样做,如果我有20种类型(如任务可能微不足道)
ATM i just copied pasted it but 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
}
}