类隐式转换

and*_*eer 0 c# casting type-inference implicit-typing

我知道我可以使用类的隐式转换,如下所示,但有没有办法让一个实例返回没有强制转换或转换的字符串?

public class Fred
{
    public static implicit operator string(Fred fred)
    {
        return DateTime.Now.ToLongTimeString();
    }
}

public class Program
{
    static void Main(string[] args)
    {
        string a = new Fred();
        Console.WriteLine(a);

        // b is of type Fred. 
        var b = new Fred(); 

        // still works and now uses the conversion
        Console.WriteLine(b);    

        // c is of type string.
        // this is what I want but not what happens
        var c = new Fred(); 

        // don't want to have to cast it
        var d = (string)new Fred(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

Meh*_*ari 8

事实上,编译器将隐式转换Fredstring但由于您使用var关键字声明变量,编译器将不知道您的实际意图.您可以将变量声明为字符串,并将值隐式地转换为字符串.

string d = new Fred();
Run Code Online (Sandbox Code Playgroud)

换句话说,您可能已经为不同类型声明了十几个隐式运算符.您希望编译器能够在其中一个之间进行选择吗?编译器将默认选择实际类型,因此根本不必执行转换.