如何比较声明为type的两个对象的类型。
我想知道两个对象是属于同一类型还是来自同一个基类。
任何帮助都是非常感谢的。
例如:
private bool AreSame(Type a, Type b) {
}
发布于 2009-04-02 03:53:57
如果您希望两个对象实例属于某个类型,也可以使用"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
发布于 2009-04-02 05:24:57
我尝试了以下使用接口和具体类的层次结构。它遍历其中一个类型的基类链,直到到达"object“,在那里我们检查当前的目标类型是否可赋值给源类型。我们还检查这些类型是否有一个公共接口。如果他们这样做了,他们就会“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());
}
}
https://stackoverflow.com/questions/708205
复制相似问题