我可以使用通用的隐式或显式运算符吗? C# [英] Can i use a generic implicit or explicit operator? C#

查看:149
本文介绍了我可以使用通用的隐式或显式运算符吗? 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
    }
}

这篇关于我可以使用通用的隐式或显式运算符吗? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆