类隐式转换

时间:2009-05-13 20:03:37

标签: 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(); 
    }
}

4 个答案:

答案 0 :(得分:8)

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

string d = new Fred();

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

答案 1 :(得分:1)

使用隐式运算符(您有),您应该只能使用:

 string d = new Fred(); 

答案 2 :(得分:1)

你想要

var b = new Fred();

是fred类型,

var c = new Fred();

是字符串类型?即使声明是相同的吗?

正如其他海报所提到的,当你声明一个新的Fred()时,它将是Fred类型,除非你给一些指示它应该是string

答案 3 :(得分:0)

不幸的是,在示例中,c 是Fred类型的。虽然弗雷德斯可以演员阵容,但最终,c是弗雷德。要强制d为字符串,您必须告诉它将Fred转换为字符串。

如果你真的希望c成为一个字符串,为什么不把它声明为一个字符串呢?