Java 的 getClass()、isAssignableFrom() 等的 c# 等效项是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1558795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the c# equivalents of of Java's getClass(), isAssignableFrom(), etc.?
提问by peter.murray.rust
I am translating from Java to C# and have code similar to:
我正在从 Java 转换为 C#,并且代码类似于:
Class<?> refClass = refChildNode.getClass();
Class<?> testClass = testChildNode.getClass();
if (!refClass.equals(testClass)) {
....
}
and elsewhere use Class.isAssignableFrom(Class c)... and similar methods
和其他地方使用Class.isAssignableFrom(Class c)......和类似的方法
Is there a table of direct equivalents for class comparsion and properties and code-arounds where this isn't possible?
是否有一个类比较、属性和代码周围的直接等价物表,这是不可能的?
(The <?>is simply to stop warnings from the IDE about generics. A better solution would be appreciated)
(这<?>只是为了停止来自 IDE 的关于泛型的警告。更好的解决方案将不胜感激)
回答by elder_george
Type refClass = refChildNode.GetType();
Type testClass = testChildNode.GetType();
if (!refClass.Equals(testClass))
{
....
}
Have a look on System.Type class. It have methods you need.
看看 System.Type 类。它有您需要的方法。
回答by Dunc
Firstly, to get the class (or in .NET speak, Type) you can use the following method:
首先,要获取类(或在 .NET 中为Type),您可以使用以下方法:
Type t = refChildNode.GetType();
Now you have the Type, you can check equality or inheritance. Here is some sample code:
现在您有了类型,您可以检查相等性或继承性。下面是一些示例代码:
public class A {}
public class B : A {}
public static void Main()
{
Console.WriteLine(typeof(A) == typeof(B)); // false
Console.WriteLine(typeof(A).IsAssignableFrom(typeof(B))); // true
Console.WriteLine(typeof(B).IsSubclassOf(typeof(A))); // true
}
This uses the System.Reflection functionality. The full list of available methods is here.
这使用 System.Reflection 功能。可用方法的完整列表在这里。
回答by Maximilian Mayerl
Have a look at reflection (http://msdn.microsoft.com/de-de/library/ms173183(VS.80).aspx).
看看反射(http://msdn.microsoft.com/de-de/library/ms173183(VS.80).aspx)。
For example, your code would be:
例如,您的代码将是:
Type refClass = refChildNode.GetType();
Type testClass = testChildNode.GetType();
if (refClass != testClass)
{
....
}

