我想在C#中做这样的事情:
Foo test = "string";
Run Code Online (Sandbox Code Playgroud)
现在应该初始化对象.我怎样才能做到这一点?我不能让它工作,但我知道这是可能的.
您正在寻找隐式转换运算符.
public class Foo
{
public string Bar { get; set; }
public static implicit operator Foo(string s)
{
return new Foo() { Bar = s };
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
Foo f = "asdf";
Console.WriteLine(f.Bar); // yields => "asdf";
Run Code Online (Sandbox Code Playgroud)