问题描述
是否有可能,而无需创建一个实例来获得价值?
Is it possible to get value without creating an instance ?
我有这个类:
public class MyClass
{
public string Name{ get{ return "David"; } }
public MyClass()
{
}
}
现在我需要得到国宝,没有的MyClass创建实例。
Now I need get the value "David", without creating instance of MyClass.
推荐答案
真正的答案:没有。这是一个的实例的属性,所以你只能把它的一个实例。您应该创建一个实例,或者使静态财产如在其他的答案。
Real answer: no. It's an instance property, so you can only call it on an instance. You should either create an instance, or make the property static as shown in other answers.
请参阅有关静态和实例成员之间的差异的更多信息。
See MSDN for more information about the difference between static and instance members.
舌头在脸颊,但仍然正确答案
是否有可能,而无需创建一个实例来获得价值?
是的,但只能通过一些非常可怕的code创造一些IL传递空
为这个
(你不要在你的财产使用),使用<$c$c>DynamicMethod$c$c>.示例code:
Yes, but only via some really horrible code which creates some IL passing in null
as this
(which you don't use in your property), using a DynamicMethod
. Sample code:
// 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());
}
}
请不要这样做。 自从这是可怕的。应该践踏,切成小块,放火,然后再切开。虽然有趣,不是吗? ;)
Please don't do this. Ever. It's ghastly. It should be trampled on, cut up into little bits, set on fire, then cut up again. Fun though, isn't it? ;)
这工作,因为它使用呼叫
而不是 callvirt
。通常情况下,C#编译器会使用 callvirt
调用的,即使它没有调用虚拟成员的,因为得到免费空引用检查(据作为IL流而言)。像这样的非虚拟调用的不的检查无效首先,它只是调用成员。如果选中这个
属性调用中,你会发现它是空。
This works because it's using call
instead of callvirt
. Normally the C# compiler would use a callvirt
call even if it's not calling a virtual member because that gets null reference checking "for free" (as far as the IL stream is concerned). A non-virtual call like this doesn't check for nullity first, it just invokes the member. If you checked this
within the property call, you'd find it's null.
编辑:正如克里斯·辛克莱指出,可以更简单地使用开放式的委托实例做到这一点:
As noted by Chris Sinclair, you can do it more simply using an open delegate instance:
var method = typeof(MyClass).GetProperty("Name").GetGetMethod();
var openDelegate = (Func<MyClass, string>) Delegate.CreateDelegate
(typeof(Func<MyClass, string>), method);
Console.WriteLine(openDelegate(null));
(但同样,请不要!)
(But again, please don't!)
这篇关于C#中获取,而无需创建实例属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!