具有类似类的C#泛型

时间:2014-07-10 23:09:55

标签: c# generics macros

假设我有一个C#类,如:

class MyClass
{
    String a, b, c, d;
    int e, f, g, h;
}

现在假设我也有:

class OtherClass1
{
    String a, b, c, d;
    int e, f, g, h;
}

和相同定义的OtherClass2,OtherClass3等,直到Otherclass50。所有这些类都具有相同的属性。但是它们是不同的类,因为它们是从WSDL自动生成的。

我需要像

这样的方法
CopyTo<T> (T target, MyClass source) 
{
    target.a = source.a; target.b = source.b;   etc...
} 

其中T可能是Otherclass1或Otherclass2等。我该如何做到这一点?这在C宏中很容易做到,但这是C#(特别是带有Compact Framework 3.5的vs2008)。

由于

5 个答案:

答案 0 :(得分:1)

我可以想到两种方法,但其中一种方法需要对这些类进行一些小改动:

1)创建一个界面

interface IMyClass { 
    String a,b,c,d;
    int e, f, g, h;
}

现在让所有类实现此接口。然后CopyTo将接受IMyClass,您就完成了。

2)使用CopyTo<T>(T target, ...)函数中的反射来复制值。

答案 1 :(得分:0)

如果效果不重要,您可以使用此帖子中的“MapAllFields”:C#. Set a member object value using reflection

答案 2 :(得分:0)

这可能有所帮助。

class MyClass
{
    public String a, b, c, d;
    public int e, f, g, h;

    // This function can be replaced with
    // public static void CopyTo(BaseClass target, MyClass source){...}
    public static void CopyTo<T>(T target, MyClass source) where T : BaseClass
    {
         target.a = source.a;
         target.b = source.b;
         target.c = source.c;
         target.d = source.d;
         target.e = source.e;
         target.f = source.f;
         target.g = source.g;
         target.h = source.h;
    }
}

class BaseClass
{
    public String a, b, c, d;
    public int e, f, g, h;

    public void CopyFrom(MyClass source)
    {
        a = source.a;
        b = source.b;
        c = source.c;
        d = source.d;
        e = source.e;
        f = source.f;
        g = source.g;
        h = source.h;
    }
}

class OtherClass1 : BaseClass
{
    //String a, b, c, d;
    //int e, f, g, h;
}

答案 3 :(得分:0)

可以使用DynamicMap()功能建议AutoMapper

var otherClass1 = Mapper.DynamicMap<OtherClass1>(myClass);

这将使您无法编写自己的对象到对象映射器,定义映射等。

进一步阅读:http://lostechies.com/jimmybogard/2009/04/15/automapper-feature-interfaces-and-dynamic-mapping/

您可能会获得与其他对象 - 对象映射框架(如EmitMapper)类似的行为。

答案 4 :(得分:0)

这会对你有帮助吗?

 class genericClass<T,U>
 {
    public T a ;
    public U e;
 }

    static void Main(string[] args)
    {
        genericClass<string, int> gen1 = new genericClass<string, int>();
        genericClass<string, int> gen2 = new genericClass<string, int>();
        genericClass<string, int> source = new genericClass<string, int>();
        source.a = "test1";
        source.e = 1;


        Copy<string,int>(gen1, source);
        Copy<string, int>(gen2, source);

        Console.WriteLine(gen1.a + " " + gen1.e);
        Console.WriteLine(gen2.a + " " + gen2.e);

        Console.ReadLine();
    }

    static void Copy<T, U>(genericClass<T, U> dest, genericClass<T, U> source)
    {
        dest.a = source.a;
        dest.e = source.e;
    }