0

参照しているアセンブリの一部であるクラスがあります。そのタイプのオブジェクトを、参照しているクラスを実装する独自のクラスに変換したい

私の参照が持っているとしましょう

public class customer
{
public string name {get;set}
public string address{get;set}
}

そして私は作成しました

public class mycustomer : customer
{
 public string name {get; set}
 public string address{get;set}
 public string email {get;set}
}

リフレクションの使用について読んだことがありますが、実際に自分で書くには十分ではありません。

PS。命名規則のセマンティクスを止めてください - これはその場での大まかな理論的な例です (ここでは命名規則を気にせず、実際のコードでのみ) 事前に感謝します

編集:とにかくこれを行うことができないことがわかりました。シリアライズ可能属性を持たないオブジェクトをシリアライズする必要があり、そのクラスをミラーリングしてシリアライズ可能にできると思っていましたが、このクラス内のプロパティの一部にシリアライズ可能属性がないことに気付きました。

とにかくありがとう - 質問に対する最良の回答を回答/Alexとしてマークします

4

4 に答える 4

3

自分で書く必要はありません。この汎用アルゴリズムでリフレクションを使用して、Customer のプロパティを MyCustomer オブジェクトにコピーできます。

    public B Convert<A, B>(A element) where B : A, new()
    {
        //get the interface's properties that implement both a getter and a setter
        IEnumerable<PropertyInfo> properties = typeof(A)
            .GetProperties()
            .Where(property => property.CanRead && property.CanWrite).ToList();

        //create new object
        B b = new B();

        //copy the property values to the new object
        foreach (var property in properties)
        {
            //read value
            object value = property.GetValue(element);

            //set value
            property.SetValue(b, value);
        }

        return b;
    }

AutoMapper のような本格的なライブラリを 1 つのシナリオだけに使用するのは、少しやり過ぎだと思います。

于 2013-08-30T10:09:43.240 に答える
3

mycustomerから継承されたメンバが既にありcustomerます。これらのメンバーを非表示にしないでください:

public class customer
{
    public string name { get; set; }
    public string address { get; set; }
}

public class mycustomer : customer
{ 
    // name and address are inherited
    public string email { get; set; }
}

現在mycustomerIS Acustomerであり、この変換に問題はありません - のインスタンスを型のmycustomer変数に代入するだけですcustomer:

mycustomer mc = new mycustomer();
customer c = mc;

それらを逆に変換するのは奇妙です。したがって、プロパティがなく、表示されcustomerませemailん。基本型によって提供されるデータしかないため、ここでは単純に基本型を使用します。ただし、顧客が実際にmycustomerインスタンスである場合 (上記のコードを参照)、必要なのはキャストだけです。

mycustomer mc2 = (mycustomer)c;

ところで、C# では、型名とパブリック メンバーに PascalNaming を使用します。

于 2013-08-30T09:47:37.017 に答える
0

簡単な方法!

public class ClassA
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
        public string note { get; set; }
    }

 public class ClassB
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
        public string note { get; set; }
        public int index { get; set; }
    }

static void Main(string[] args)
        {
           //create an object with ClassA  type
            ClassA a = new ClassA { id=1,age=12,name="John",note="good"};
            ClassB b=a.Cast<ClassB>();
        }

「キャスト」メソッドの実装は、このビデオ https://www.youtube.com/watch?v=XUqfg9albdAに従ってください

于 2016-05-31T16:47:52.060 に答える