<分区>
我想在 C# 中做这样的事情:
Foo test = "string";
现在对象应该被初始化了。我怎样才能做到这一点?我无法让它工作,但我知道这是可能的。
<分区>
我想在 C# 中做这样的事情:
Foo test = "string";
现在对象应该被初始化了。我怎样才能做到这一点?我无法让它工作,但我知道这是可能的。
最佳答案
您正在寻找隐式转换运算符。
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";
关于c# - 如何在不使用 new 的情况下直接赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23789398/