Yeg*_*gor 92 .net c# static-methods types
在我可以使用的非静态方法中this.GetType()
,它将返回Type
.如何Type
在静态方法中获得相同的内容?当然,我不能只写,typeof(ThisTypeName)
因为ThisTypeName
只在运行时才知道.谢谢!
Jar*_*Par 129
如果您正在寻找与this.GetType()
静态方法相当的1衬里,请尝试以下方法.
Type t = MethodBase.GetCurrentMethod().DeclaringType
Run Code Online (Sandbox Code Playgroud)
虽然这可能比仅仅使用昂贵得多typeof(TheTypeName)
.
Jon*_*eet 58
还有一些其他答案尚未明确澄清的内容,这与您在执行时仅提供类型的想法相关.
如果使用派生类型执行静态成员,则二进制文件中将省略实际类型名称.例如,编译此代码:
UnicodeEncoding.GetEncoding(0);
Run Code Online (Sandbox Code Playgroud)
现在使用ildasm ...你会看到调用是这样发出的:
IL_0002: call class [mscorlib]System.Text.Encoding
[mscorlib]System.Text.Encoding::GetEncoding(int32)
Run Code Online (Sandbox Code Playgroud)
编译器解决了调用Encoding.GetEncoding
- 没有UnicodeEncoding
左边的痕迹.这让你对"当前类型"的想法毫无意义,我担心.
Rob*_*erc 24
另一种解决方案是使用自引导类型
//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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在继承它的类中,我创建一个自引用类型:
public class Child: Parent<Child>
{
}
Run Code Online (Sandbox Code Playgroud)
现在,Parent内部的调用类型typeof(TSelfReferenceType)将获取并返回调用者的Type而无需实例.
Child.GetType();
Run Code Online (Sandbox Code Playgroud)
-抢
您不能this
在静态方法中使用,因此无法直接使用.但是,如果您需要某个对象的类型,只需调用GetType
它并使this
实例成为您必须传递的参数,例如:
public class Car {
public static void Drive(Car c) {
Console.WriteLine("Driving a {0}", c.GetType());
}
}
Run Code Online (Sandbox Code Playgroud)
不过,这似乎是一个糟糕的设计.你确定你真的需要在自己的静态方法中获取实例本身的类型吗?这看起来有点奇怪.为什么不使用实例方法?
public class Car {
public void Drive() { // Remove parameter; doesn't need to be static.
Console.WriteLine("Driving a {0}", this.GetType());
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
60333 次 |
最近记录: |