-
21-08-2019 - |
题
我知道我可以使用隐式转换与类如下,但有什么办法,我可以得到一个实例,不进行强制转换或转换返回一个字符串?
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();
}
}
解决方案
事实上,编译器会隐式转换Fred
到string
但因为你与var
关键字声明变量,编译器就没有你的实际意图的想法。你可以声明你的变量为字符串和具有值隐含强制转换为字符串。
string d = new Fred();
换句话说,你可能宣布针对不同类型的十几隐含运营商。如何你所期望的编译器可以其中之一之间做出选择?编译器会选择默认情况下的实际类型,因此它不会在所有执行强制类型转换。
其他提示
使用一个隐含的操作者(其必须)你应该只能够使用:
string d = new Fred();
您想
var b = new Fred();
为类型佛瑞德的,和
var c = new Fred();
是字符串类型?尽管声明是相同?
如由其他海报提到的,当声明一个新佛瑞德(),这将是类型佛瑞德的,除非你给一些指示它应该是一个string
不幸的是,在该示例中,C 是类型佛瑞德的。虽然FREDS可以转换为字符串,最终,c是弗雷德。要强制d为一个字符串,你必须告诉它投下的弗雷德为字符串。
如果你真的想为C的字符串,为什么不干脆宣布它作为一个字符串?
不隶属于 StackOverflow