如何在不使用新的情况下进行直接分配?

use*_*544 2 c# assign

我想在C#中做这样的事情:

Foo test = "string";
Run Code Online (Sandbox Code Playgroud)

现在应该初始化对象.我怎样才能做到这一点?我不能让它工作,但我知道这是可能的.

Mik*_*ran 8

您正在寻找隐式转换运算符.

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)