Duplicate(), , , Duplicate(), int.
, , . ( )
[TestMethod]
public void TestMethod1()
{
var myObject = new AnObject { AString = "someString" };
var myOtherObject = new AnotherObject();
var newObject = myObject.Duplicate(myOtherObject);
Assert.IsTrue(newObject.AString=="someString");
var newObject2 = myObject.Duplicate(1);
Assert.IsTrue(newObject2 is Int32);
}
Duplicate() , -, , , -.
Duplicate():
public class AnObject
{
public string AString { get; set; }
public T Duplicate<T>(T exampleObject)
where T: new()
{
var newInstance = (T)Activator.CreateInstance<T>();
if (typeof (T) == typeof (AnotherObject))
{
var another = newInstance as AnotherObject;
if(another!=null)
another.AString = this.AString;
}
return newInstance;
}
}
, AnotherObject.
public class AnotherObject
{
public string AString { get; set; }
}
Duplicate(), , , , int. , , Duplicate() int (, , nullable int).
It works well for reference types (classes).
source
share