是否可以在不创建实例的情况下获取值(value)?
我有这门课:
public class MyClass
{
public string Name{ get{ return "David"; } }
public MyClass()
{
}
}
现在我需要在不创建 MyClass 实例的情况下获取值“David”。
最佳答案
真正的答案:没有。这是一个实例 属性,因此您只能在实例上调用它。您应该创建一个实例,或者将属性设为静态,如其他答案中所示。
有关静态成员和实例成员之间差异的更多信息,请参阅 MSDN。
开玩笑但仍然是正确答案:
Is it possible to get value without creating an instance ?
是的,但只能通过一些非常糟糕的代码创建一些 IL,将 null
作为 this
(您不在您的属性中使用),使用 DynamicMethod
.示例代码:
// Jon Skeet explicitly disclaims any association with this horrible code.
// THIS CODE IS FOR FUN ONLY. USING IT WILL INCUR WAILING AND GNASHING OF TEETH.
using System;
using System.Reflection.Emit;
public class MyClass
{
public string Name { get{ return "David"; } }
}
class Test
{
static void Main()
{
var method = typeof(MyClass).GetProperty("Name").GetGetMethod();
var dynamicMethod = new DynamicMethod("Ugly", typeof(string),
Type.EmptyTypes);
var generator = dynamicMethod.GetILGenerator();
generator.Emit(OpCodes.Ldnull);
generator.Emit(OpCodes.Call, method);
generator.Emit(OpCodes.Ret);
var ugly = (Func<string>) dynamicMethod.CreateDelegate(
typeof(Func<string>));
Console.WriteLine(ugly());
}
}
请不要这样做。 曾经。太可怕了。它应该被踩踏,切成小块,着火,然后再切开。不过很有趣,不是吗? ;)
之所以可行,是因为它使用的是 call
而不是 callvirt
。通常 C# 编译器会使用 callvirt
调用 即使它没有调用虚拟成员 因为它“免费”获得空引用检查(就 IL 流而言).像这样的非虚拟调用不会首先检查是否为空,它只是调用成员。如果您在属性调用中检查了 this
,您会发现它为 null。
编辑:正如 Chris Sinclair 所指出的,您可以使用开放委托(delegate)实例更简单地完成此操作:
var method = typeof(MyClass).GetProperty("Name").GetGetMethod();
var openDelegate = (Func<MyClass, string>) Delegate.CreateDelegate
(typeof(Func<MyClass, string>), method);
Console.WriteLine(openDelegate(null));
(但再次强调,请不要这样做!)
关于C# 在不创建实例的情况下获取属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11162652/