2017-03-29 56 views

回答

3

反思是不是太多慢...(這應該只是一點點慢於virtual方法調用):

例子:

public class MyClass 
{ 
    internal int MyProperty { get; set; } 
} 

而且然後:

public static class MyClassAccessor 
{ 
    public static readonly Func<MyClass, int> GetMyProperty; 
    public static readonly Action<MyClass, int> SetMyProperty; 

    static MyClassAccessor() 
    { 
     var prop = typeof(MyClass).GetProperty("MyProperty", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); 
     GetMyProperty = (Func<MyClass, int>)Delegate.CreateDelegate(typeof(Func<MyClass, int>), prop.GetMethod); 
     SetMyProperty = (Action<MyClass, int>)Delegate.CreateDelegate(typeof(Action<MyClass, int>), prop.SetMethod); 
    } 
} 

而且你使用像:

var mc = new MyClass(); 
MyClassAccessor.SetMyProperty(mc, 5); 
Console.WriteLine(MyClassAccessor.GetMyProperty(mc)); 
+0

感謝您的明確解釋 –

相關問題