簡體   English   中英

具有類似類的C#泛型

[英]C# generic with similar classes

假設我有一個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)。

謝謝

我可以想到兩種方法,但是其中一種方法需要對類進行一些小的更改:

1)創建一個界面

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

現在,使您所有的類都實現此接口。 然后, CopyTo將接受IMyClass ,您已完成。

2)在CopyTo<T>(T target, ...)函數中使用反射來復制值。

如果性能不是很關鍵,則可以使用此發布中的“ MapAllFields”: C#。 使用反射設置成員對象值

這可能會有所幫助。

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;
}

可以通過它的DynamicMap()功能建議AutoMapper

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

這將使您不必編寫自己的對象到對象映射器,定義映射等。

進一步閱讀: http : //lostechies.com/jimmybogard/2009/04/15/automapper-feature-interfaces-and-dynamic-mapping/

使用其他對象-對象映射框架(例如EmitMapper)也可能會獲得類似的行為。

這對您有幫助嗎?

 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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM