在C#中传递Object的不同方法

时间:2013-12-11 11:30:22

标签: c# class new-operator

我需要澄清一个对象可以从C#中的方法返回的方式。我有以下课程;

public class Person
{
    public string Forename {get;set;}
    public string Surname {get;set;}
}

我的通用功能是;

public static Person MyFunction()
{
    Person oPerson = new Person();
    oPerson.Forename = "Joe";
    oPerson.Surname = "King";
    return oPerson;
}

以下两个电话之间是否有任何不同

Person oPerson = new Person();
oPerson = MyFunction();

Person oPerson = MyFunction();

调用像

这样的新运算符是否正确
Person oPerson = new Person();

即使泛型函数正在创建此对象的新实例并将其返回。

2 个答案:

答案 0 :(得分:1)

首先,你的电话不一样。

Person oPerson = new Person(); // This object is about to be discarded by...
oPerson = MyFunction(); // ... Overwriting the reference to it here

此时,您创建的第一个Person可以被垃圾收集器清理。

如果您有默认初始化,则应该在Person的构造函数中执行此操作。

答案 1 :(得分:0)

不,oPerson中的结果对象应该完全相同。我能看到的唯一区别是,

Person oPerson = new Person();
oPerson = MyFunction();

需要更多时间来执行,因为您要创建对象两次。

但是,我看不到你的功能

public static Person MyFunction()
{
    Person oPerson = new Person();
    oPerson.Forename = "Joe";
    oPerson.Surname = "King";
    return oPerson;
}

是通用的,因为它只处理一种类型。通用函数如下所示:

public static <T> SomeGenericFunction(T person) where T : Person
{
    person.Forename = "Joe";
    person.Surname = "King";
    return person;

}