透過 Activator 實現反射
LinqPad
void Main()
{
var PersonObj = Activator.CreateInstance(typeof(Person));
var FakePersonObj = Activator.CreateInstance(typeof(FakePerson));
if (PersonObj is Person)
{
PersonObj.Dump();
}
if (FakePersonObj is FakePerson)
{
FakePersonObj.Dump();
var fakePerson = (FakePerson)FakePersonObj;
var fakePerson2 = FakePersonObj as FakePerson;
}
////無效轉換,拋錯
try
{
var Person = (FakePerson)PersonObj;
Person.Dump();
}
catch (Exception ex)
{
ex.Dump();
}
//// as example
try
{
var Person2 = PersonObj as FakePerson;
Person2.Dump();
}
catch (Exception ex)
{
ex.Dump();
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set;}
}
public class FakePerson
{
public int ID { get; set; }
public string NickName { get; set; }
}
相關參考
余小章 : [C#.NET] 利用 dynamic 簡化反射程式碼?
如果有任何錯誤或者引用問題請麻煩告知 !!!