我知道我可以对类使用隐式转换,如下所示,但是有没有方法可以让一个实例返回一个字符串,而不需要强制转换或转换?
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();
}
}发布于 2009-05-13 20:04:35
事实上,编译器会隐式地将Fred转换为string,但是因为您使用var关键字声明变量,所以编译器不会知道您的实际意图。您可以将变量声明为string,并将值隐式转换为string。
string d = new Fred();换句话说,您可能为不同的类型声明了12个隐式运算符。你怎么能期望编译器能够在它们之间做出选择呢?编译器将默认选择实际的类型,因此它根本不需要执行强制转换。
发布于 2009-05-13 20:04:48
使用隐式运算符(您已有),您应该能够使用:
string d = new Fred(); 发布于 2009-05-13 20:06:11
你想要的
var b = new Fred();
类型为fred,并且
var c = new Fred();
是字符串类型吗?即使声明是相同的?
正如其他发布者所提到的,当您声明一个新的Fred()时,它将是Fred类型,除非您给出一些指示它应该是一个string
https://stackoverflow.com/questions/860118
复制相似问题