【问题标题】:Instantiate and return an object in one line [duplicate]在一行中实例化并返回一个对象[重复]
【发布时间】:2019-09-09 17:08:05
【问题描述】:

下面的代码有效,显示了当对象被实例化时对象的返回。为什么这行得通?在我看来,我可以理解“Return new ...”,或者在单独的行上实例化 Dummy1 和“Return Dummy1”。

    public class TestClass1
    {
        public string s = "test2";
    }

    public TestClass1 GetTestClass()
    {
        TestClass1 dummy1;
        return dummy1 = new TestClass1();         //  Why is this valid?
    }

【问题讨论】:

标签: c#


【解决方案1】:

这是因为在 C# 中,赋值也是产生值的表达式。

试试这个:

public class Program
{
    public static void Main()
    {
        var str1 = "foo";
        var str2 = (str1 = "bar");
        Console.WriteLine(str2);
    }
}

您会看到str2 将保存str1 的值,而"bar" 的值将被赋值。

【讨论】:

    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 2018-12-13
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多