簡體   English   中英

比較從不同程序集加載的對象

[英]Compare objects loaded from different assemblies

我有一些應該按照設計來自遠程程序集的對象類。 我希望能夠比較這些類的實例是否相等,即使實例是從不同的程序集加載的。 在現實生活中,這些將從網絡位置或網絡加載,我想與本地緩存進行比較。 我使用序列化和自定義序列化綁定器的解決方案獲得了一些好結果。

我用來進行比較的示例客戶端代碼是:

    Assembly a = Assembly.LoadFile(@"c:\work\abc1\abc.dll");
    Type t1 = a.GetType("Abc.Def");
    Assembly b = Assembly.LoadFile(@"c:\work\abc2\abc.dll");
    Type t2 = b.GetType("Abc.Def");
    Object o1 = t1.GetConstructors()[0].Invoke(null);
    Object o2 = t2.GetConstructors()[0].Invoke(null);
    Console.WriteLine(o1.Equals(o2));

我在我的程序集中使用的模式是:

namespace Abc
{
    internal sealed class DefBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            Type ttd = null;
            try
            {
                ttd = this.GetType().Assembly.GetType(typeName);
            }
            catch (Exception any)
            {
                Debug.WriteLine(any.Message);
            }
            return ttd;
        }
    }


    [Serializable]
    public class Def
    {
        public Def()
        {
            Data = "This is the data";
        }
        public String Data { set; get; }
        public override bool Equals(object obj)
        {
            if (obj.GetType().FullName.Equals(this.GetType().FullName))
            {
                try
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    bf.Serialize(ms, obj);
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
                    bf.Binder = new Abc.DefBinder();
                    Abc.Def that = (Abc.Def)bf.Deserialize(ms);
                    if (this.Data.Equals(that.Data))
                    {
                        return true;
                    }
                }
                catch (Exception any) {
                    Debug.WriteLine(any.Message);
                }
            }
            return false;
        }
    }
}

我的問題是 :這似乎有效,但它感覺很hacky,那么是否有更直接的方法來比較可能從不同程序集加載的對象?

這有些苛刻,但是能夠快速簡便地完成工作。 你可以做的另一件事是使用大量的反射來為兩個給定的類型編寫一個相等的方法。 就像是:

public bool Equals(Type t1, Type t2)
{
    var t1Constructors = t1.GetConstructors();
    var t2Constructors = t2.GetConstructors();
    //compare constructors
    var t1Methods = t1.GetMethods();
    var t2Methods = t2.GetMethods();
    //compare methods
    //etc.
}

依此類推,使用BindingFlags獲取屬性/方法/等。 你關心並檢查每個人的平等。 當然不是很容易,但它會給你很大的靈活性來確定你的特定用例中“平等”的真正含義。

暫無
暫無

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

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