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

时间:2014-05-21 16:52:15

标签: c# assign

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

Foo test = "string";

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

2 个答案:

答案 0 :(得分:8)

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

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";

答案 1 :(得分:0)

您可以隐式使用强制转换运算符:

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";