0

我正在尝试创建一个通用方法,我必须将一些字符串附加到通用数据类型并创建该附加字符串的实例。

例如:我有两个类 Object1、Object2、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();

}

有什么办法可以使用 CSharp 来做到这一点?

4

2 回答 2

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# 才能提出一个好的问题,因为就目前而言,这个问题似乎令人困惑和不一致。

于 2012-06-16T19:05:34.163 回答
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()方法。

于 2012-06-16T18:33:35.723 回答