1

如何将一个对象的所有属性设置为与另一个相等?就像在我的例子中一样,TCar 基本上是一辆汽车,我怎样才能将共享变量设置为相等?如果我没记错的话,在 Java 中,我可以很容易地做到这一点。

class Car {

}

class TCar : Car {

}

Car car = new Car();
TCar datcar = new TCar();
datcar = car; Error? Isn't the datcar is a 'Car' too?

我不想手动设置所有内容。

4

4 回答 4

5

您的代码将不起作用,因为 aCar不是TCar. 反之亦然:car = datcar.

但是,这可能不会达到您的预期,因为它只会产生两个引用 cardatcar指向同一个TCar对象。

如果您想将对象保持为单独的对象,但使用另一个对象的属性值更新一个对象的所有属性,则必须一一分配它们。或者您可以使用AutoMapper,它会自动执行此操作。

于 2013-11-12T20:13:47.573 回答
4

datacar是 a Car,但它特别是 aTCar所以不能将对它的引用car设置为它,因为它们在内存中的类型不同。此外,您所做的不会设置属性值,它只会在内存中设置引用(或指针)。

您正在寻找的是Clone另一种类型。考虑添加一个扩展方法来克隆该对象,如下所示:

namespace System
{
    public static class Extensions
    {
        public static TOut Clone<TOut>(this Car input) where TOut : Car
        {
            var o = Activator.CreateInstance(typeof(TOut));
            foreach (var prop in typeof(Car).GetProperties())
            {
                prop.SetValue(o, prop.GetValue(input));
            }
        }
    }
}

所以现在你可以这样做:

TCar datacar = car.Clone<TCar>();
于 2013-11-12T20:13:30.433 回答
3

您可以使用另一个对象的属性创建一个新对象:

Car car = new Car("jeep");

TCar datCar = new Tcar {
 Brand = car.Brand
};

或者您可以创建显式/隐式运算符或使用 AutoMapper 之类的映射工具。

于 2013-11-12T20:13:21.373 回答
0

In C# you'll need conversion operators - and, in the case you mentioned, it would be an Implicit conversion.

Quoting from MSDN: "C# enables programmers to declare conversions on classes or structs so that classes or structs can be converted to and/or from other classes or structs, or basic types. Conversions are defined like operators and are named for the type to which they convert. Either the type of the argument to be converted, or the type of the result of the conversion, but not both, must be the containing type."

It would look something like this:

class Car
{
    // ...other members 

    // User-defined conversion from TCar to Car
    public static implicit operator Car(TCar d)
    {
        return new Car(d);
    }
    //  User-defined conversion from Car to TCar
    public static implicit operator TCar(Car d)
    {
        return new TCar(d);
    }
}

Source: http://msdn.microsoft.com/en-us/library/09479473(v=vs.90).aspx

于 2013-11-12T20:29:04.347 回答