For exmaple, have a type A, how can 开发者_如何学PythonI know one of its ancester is Windows.Forms.Form?
You can use the IsSubclassOf method on Type:
var myType = typeof(Form1);
var formType = typeof(Form);
Console.WriteLine(myType.IsSubclassOf(formType)); //outputs 'true'
Something like this (untested):
var x = yourValue;
var t = x.GetType();
var p = t;
while (p.BaseType != null)
{
p = t.BaseType;
}
If you're looking for a specific type, rather than just wondering what the base is, you test for it.
var myX = x as WhateverType;
if (myX != null)
{
// Use myX
}
In .NET, it's "lowest ancestor" will always be the universal base class, Object
. Can you rephrase your question?
Here is one shortcut for checking for an ancestor relationship between types. That is, A is derived from Form if a variable of type Form can refer to A:
Type aType=typeof(A);
...
bool isFormAnAncestorOfA = typeof(Form).IsAssignableFrom(aType);
精彩评论