3 回答

TA貢獻1946條經驗 獲得超3個贊
如果您要尋找與this.GetType()靜態方法等效的1襯管,請嘗試以下方法。
Type t = MethodBase.GetCurrentMethod().DeclaringType
盡管這可能比僅使用更昂貴typeof(TheTypeName)。

TA貢獻1895條經驗 獲得超7個贊
還有一些其他答案尚未完全弄清,這與您只在執行時可用的類型的想法有關。
如果使用派生類型執行靜態成員,則在二進制文件中將省略實類型名稱。因此,例如,編譯以下代碼:
UnicodeEncoding.GetEncoding(0);
現在在其上使用ildasm ...,您將看到發出如下調用:
IL_0002: call class [mscorlib]System.Text.Encoding
[mscorlib]System.Text.Encoding::GetEncoding(int32)
編譯器已解決對的調用Encoding.GetEncoding-沒有UnicodeEncoding剩余痕跡??峙逻@會使您對“當前類型”的想法變得荒謬。

TA貢獻1820條經驗 獲得超9個贊
另一種解決方案是使用自引用類型
//My base class
//I add a type to my base class use that in the static method to check the type of the caller.
public class Parent<TSelfReferenceType>
{
public static Type GetType()
{
return typeof(TSelfReferenceType);
}
}
然后在繼承它的類中,創建一個自引用類型:
public class Child: Parent<Child>
{
}
現在,Parent內部的調用類型typeof(TSelfReferenceType)將獲得并返回調用者的Type,而無需實例。
Child.GetType();
-搶
- 3 回答
- 0 關注
- 486 瀏覽
添加回答
舉報