首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#对象类型比较

C#对象类型比较
EN

Stack Overflow用户
提问于 2009-04-02 03:46:10
回答 2查看 79K关注 0票数 63

如何比较声明为type的两个对象的类型。

我想知道两个对象是属于同一类型还是来自同一个基类。

任何帮助都是非常感谢的。

例如:

代码语言:javascript
复制
private bool AreSame(Type a, Type b) {

}
EN

回答 2

Stack Overflow用户

发布于 2009-04-02 03:53:57

如果您希望两个对象实例属于某个类型,也可以使用"IS“关键字。这也适用于将子类与父类以及实现接口的类等进行比较。但这不适用于类型为type的类型。

代码语言:javascript
复制
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
票数 13
EN

Stack Overflow用户

发布于 2009-04-02 05:24:57

我尝试了以下使用接口和具体类的层次结构。它遍历其中一个类型的基类链,直到到达"object“,在那里我们检查当前的目标类型是否可赋值给源类型。我们还检查这些类型是否有一个公共接口。如果他们这样做了,他们就会“AreSame”。

希望这能有所帮助。

代码语言:javascript
复制
 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());
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/708205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档