がある:
if (myControl is MyControl)
{
var m = (MyControl)myControl;
}
これは、型階層のどの部分でも機能します。変数自体が基本型の場合、次のチェックは機能しません。
MyBaseControl myControl = null;
if (myControl.GetType() == typeof(MyControl))
{
}
ただし、オーバーライドされたメソッドまたはプロパティの動作が必要なようです。通常の状況では、オーバーライドしますVisible
:
public override bool Visible
{
get { return true; } // Always visible in derived class.
}
ただし、これは、基本クラスがシールされておらず、オーバーライドするメンバーがabstract
またはである場合のみvirtual
です。そうでない場合は、派生型へのキャストに固執します...理想的ではありませんが、多くのオプションはありません。
次のように基本メンバーを非表示にしようとしたようにも聞こえます。
public new bool Visible
{
get { return true; }
}
これは、型自体への参照がある場合にのみ機能します。基本型への参照がある場合、メンバーの非表示は機能せず、メンバーが派生型で非表示になっていることを知りません。
MyBaseControl c = new MyDerivedControl();
bool vis = c.Visible; // Comes from MyBaseControl even if hidden in derived control.
(上記でVisible
は、オーバーライドされた場合、派生クラスから取得されます)。
更新:実行時にこれを行うには、反映したいものの名前を知っている限り、次のことを行うことができます:
class Program
{
static void Main(string[] args)
{
A a = new B();
// Get the casted object.
string fullName = a.GetType().FullName;
object castedObject = Convert.ChangeType(a, Type.GetType(fullName));
// Use reflection to get the type.
var pi = castedObject.GetType().GetProperty("Visible");
Console.WriteLine(a.Visible);
Console.WriteLine((bool)pi.GetValue(castedObject, null));
Console.Read();
}
}
class A
{
public bool Visible { get { return false; } }
}
class B : A
{
public new bool Visible { get { return true; } }
}
}