簡體   English   中英

C# Object 型號比較

[英]C# Object Type Comparison

如何比較聲明為類型的兩個對象的類型。

我想知道兩個對象是同一類型還是來自同一基礎 class。

任何幫助表示贊賞。

例如

private bool AreSame(Type a, Type b) {

}

假設ab是兩個對象。 如果您想查看ab是否在同一個 inheritance 層次結構中,請使用Type.IsAssignableFrom

var t = a.GetType();
var u = b.GetType();

if (t.IsAssignableFrom(u) || u.IsAssignableFrom(t)) {
  // x.IsAssignableFrom(y) returns true if:
  //   (1) x and y are the same type
  //   (2) x and y are in the same inheritance hierarchy
  //   (3) y is implemented by x
  //   (4) y is a generic type parameter and one of its constraints is x
}

如果您想檢查一個是否是另一個的基礎 class,請嘗試Type.IsSubclassOf

如果您知道具體的基數 class,那么只需使用is關鍵字:

if (a is T && b is T) {
  // Objects are both of type T.
}

否則,您必須直接遍歷 inheritance 層次結構。

不過,這個想法有一點問題,因為每個 object(實際上,每個類型)都有一個共同的基礎 class、Object。 您需要定義的是您想要 go 的 inheritance 鏈上多遠(無論它們是相同的還是具有相同的直系父級,或者一個是另一個的直系父級,等等)並執行您的那樣檢查。 IsAssignableFrom對於確定類型是否相互兼容很有用,但不能完全確定它們是否具有相同的父級(如果這是您所追求的)。

如果您的嚴格標准是 function 應該返回 true 如果...

  • 類型相同
  • 一種類型是另一種類型的父級(直接或其他)
  • 這兩種類型具有相同的直接父級

你可以使用

private bool AreSame(Type a, Type b) 
{
    if(a == b) return true; // Either both are null or they are the same type

    if(a == null || b == null) return false; 

    if(a.IsSubclassOf(b) || b.IsSubclassOf(a)) return true; // One inherits from the other

    return a.BaseType == b.BaseType; // They have the same immediate parent
}

如果您希望兩個 object 實例屬於某種類型,您也可以使用“IS”關鍵字。 這也適用於將子類與父類以及實現接口的類等進行比較。 不過,這不適用於 Type 類型的類型。

if (objA Is string && objB Is string)
// they are the same.

public class a {}

public class b : a {}

b objb = new b();

if (objb Is a)
// they are of the same via inheritance

我使用接口和具體類嘗試了以下層次結構。 它遍歷其中一種類型的基本 class 鏈,直到它到達“對象”,在此我們檢查當前目標類型是否可分配給源類型。 我們還檢查類型是否具有公共接口。 如果他們這樣做,那么他們'AreSame'

希望這可以幫助。

 public interface IUser
{
     int ID { get; set; }
     string Name { get; set; }
}

public class NetworkUser : IUser
{
    public int ID
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}

public class Associate : NetworkUser,IUser
{
    #region IUser Members

    public int ID
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }

    #endregion
}

public class Manager : NetworkUser,IUser
{
    #region IUser Members

    public int ID
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }

    #endregion
}


public class Program
{

    public static bool AreSame(Type sourceType, Type destinationType)
    {
        if (sourceType == null || destinationType == null)
        {
            return false;
        }

        if (sourceType == destinationType)
        {
            return true;
        }

        //walk up the inheritance chain till we reach 'object' at which point check if 
    //the current destination type is assignable from the source type      
    Type tempDestinationType = destinationType;
        while (tempDestinationType.BaseType != typeof(object))
        {
            tempDestinationType = tempDestinationType.BaseType;
        }
        if( tempDestinationType.IsAssignableFrom(sourceType))
        {
            return true;
        }

        var query = from d in destinationType.GetInterfaces() join s in sourceType.GetInterfaces()
                    on d.Name equals s.Name
                    select s;
        //if the results of the query are not empty then we have a common interface , so return true 
    if (query != Enumerable.Empty<Type>())
        {
            return true;
        }
        return false;            
    }

    public static void Main(string[] args)
    {

        AreSame(new Manager().GetType(), new Associate().GetType());
    }
}

暫無
暫無

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

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