类隐式转换
我知道我可以对类使用隐式转换,如下所示,但是有什么方法可以让实例返回字符串而无需进行强制转换或转换?
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();
}
}
I know that I can use implicit conversions with a class as follows but is there any way that I can get a instance to return a string without a cast or conversion?
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
事实上,编译器会隐式地将
Fred
转换为string
,但由于您使用var
关键字声明变量,编译器将不知道您的实际意图。 您可以将变量声明为字符串,并将值隐式转换为字符串。换句话说,您可能已经为不同类型声明了十几个隐式运算符。 您如何期望编译器能够在其中之一之间进行选择? 编译器将默认选择实际类型,因此根本不需要执行强制转换。
In fact, the compiler will implicitly cast
Fred
tostring
but since you are declaring the variable withvar
keyword the compiler would have no idea of your actual intention. You could declare your variable as string and have the value implicitly casted to string.Put it differently, you might have declared a dozen implicit operators for different types. How you'd expect the compiler to be able to choose between one of them? The compiler will choose the actual type by default so it won't have to perform a cast at all.
使用隐式运算符(您拥有),您应该能够使用:
With an implicit operator (which you have) you should just be able to use:
您希望
var b = new Fred();
为 fred 类型,而
var c = new Fred();
为字符串类型? 即使声明相同?
正如其他发帖者所提到的,当您声明一个 new Fred() 时,它将是 Fred 类型,除非您给出 some 指示它应该是一个
string
you want
var b = new Fred();
to be of type fred, and
var c = new Fred();
to be of type string? Even though the declarations are identical?
As mentioned by the other posters, when you declare a new Fred(), it will be of type Fred unless you give some indication that it should be a
string
不幸的是,在示例中,c 的类型为 Fred。 虽然 Freds 可以转换为字符串,但最终 c 是 Fred。 要将 d 强制转换为字符串,您必须告诉它将 Fred 转换为字符串。
如果你真的希望 c 是一个字符串,为什么不直接将它声明为一个字符串呢?
Unfortunately, in the example, c is of type Fred. While Freds can be cast to strings, ultimately, c is a Fred. To force d to a string, you have to tell it to cast the Fred as a string.
If you really want c to be a string, why not just declare it as a string?