我正在尝试创建一个泛型方法,我必须将一些字符串附加到Generic数据类型并创建该附加字符串的实例。
例如: 我有两节课 Object1, 对象2, Object3, Object4,.... Object100和 Object1Address, Object2Address, Object3Address, Object4Address,.... Object100Address
现在我有方法为每个对象,如MethodObject1(),MethodObject2(),MethodObject3(),MethodObject4()
MethodObject1()
{
Object1 object = new Object1();
Object1Address objectAddress = new Object1Address();
TestMethod();
}
MethodObject2()
{
Object2 object = new Object2();
Object2Address objectAddress = new Object2Address();
TestMethod();
}
MethodObject3()
{
Object3 object = new Object3();
Object3Address objectAddress = new Object3Address();
TestMethod();
}
MethodObject4()
{
Object4 object = new Object4();
Object4Address objectAddress = new Object4Address();
TestMethod();
}
.
.
.
MethodObject100()
{
Object100 object = new Object100();
Object100Address objectAddress = new Object100Address();
TestMethod();
}
但是大约有100个对象,所以我必须以类似的方式创建100个方法。 所以我想到了创建一个通用方法。
There is a method which returns only the an array of Object name from an XML file.
Eg: ObjectName[] objectName = GetObjects(); // Returns an array of Object Names from XML file so that
objectName[0] = Object1;
objectName[1] = Object2;
objectName[2] = Object3;
objectNmae[3] = Object4;
.
.
.
objectName[99] = Object100;
I am looping through objectName array
foreach(var objectItem in objectName)
{
MethodName<objectItem>();
}
In my generic method I can create an instance of object, like
MethodName<T>()
{
T t = new T();
Some how I have to get the name of T and append Address to T
So that I can create TAddress instance like
TAddress tAddress = new TAddress();
}
有什么方法可以用C sharp做到这一点吗?
答案 0 :(得分:0)
您的案例并不需要通用方法。
您可能希望覆盖类中的ToString
方法。
class PersonAddress()
{
public override string ToString()
{
return string.Concat(this.Street, ", ", this.City, ", ", this.Postcode);
}
}
class Person()
{
public override string ToString()
{
return string.Concat(this.Name, ", ", this.PersonAddress.ToString());
}
}
请注意Person
类如何重用PersonAddress.ToString()
方法。
答案 1 :(得分:0)
即使进行了编辑,我仍然无法按照您的要求进行操作。然而,为了推动前进,我将提供一个至少可以帮助你理解你想要的答案。
public class ThingWithAddress<T>
{
public T Item { get; private set; }
public string Address { get; private set; }
public static ThingWithAddress<T> Create(T item, string address)
{
return new ThingWithAddress<T>
{
Item = item,
Address = address,
};
}
}
然后你可以得到一个既有人又有地址的对象:
Person person = ...;
var personWithAddress = ThingWithAddress.Create(person, "some address");
不要采取错误的方式,但你可能需要学习足够的C#以形成一个好问题,因为就目前而言,问题似乎令人困惑和不一致。