【发布时间】:2014-07-10 11:05:38
【问题描述】:
我想在 C# 中做这样的事情:
Foo test = "string";
现在应该初始化对象。我怎样才能做到这一点?我无法让它工作,但我知道这是可能的。
【问题讨论】:
我想在 C# 中做这样的事情:
Foo test = "string";
现在应该初始化对象。我怎样才能做到这一点?我无法让它工作,但我知道这是可能的。
【问题讨论】:
您可以使用强制转换运算符来隐式:
sealed class Foo
{
public string Str
{
get;
private set;
}
Foo()
{
}
public static implicit operator Foo(string str)
{
return new Foo
{
Str = str
};
}
}
那你就可以Foo test = "string";了。
【讨论】:
Str 不存在)
您正在寻找隐式转换运算符。
public class Foo
{
public string Bar { get; set; }
public static implicit operator Foo(string s)
{
return new Foo() { Bar = s };
}
}
那么你可以这样做:
Foo f = "asdf";
Console.WriteLine(f.Bar); // yields => "asdf";
【讨论】: