我知道我可以对类使用隐式转换,如下所示,但是有什么方法可以让实例在没有强制转换或转换的情况下返回字符串?
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();
}
}