【问题标题】:How can I do direct assignment without using new? [duplicate]如何在不使用 new 的情况下进行直接分配? [复制]
【发布时间】:2014-07-10 11:05:38
【问题描述】:

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

Foo test = "string";

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

【问题讨论】:

标签: c# assign


【解决方案1】:

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

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

【讨论】:

  • +1 但您应该修复答案中的语法错误。 (Str 不存在)
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 2023-01-02
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多