2009-08-14 14 views
6

I (yansıtıcı itibaren) aşağıdaki IL genelleme çalışıyorum: DynamicMethod ile bu IL ben çalıştığınızda, ancakdeğer türleri ile ve DynamicMethod "Operasyon Çalışma zamanını destablize olabilir"

.method private hidebysig instance void SetValue(valuetype Test.TestFixture/ValueSource& thing, string 'value') cil managed 
{ 
    .maxstack 8 
    L_0000: nop 
    L_0001: ldarg.1 
    L_0002: ldarg.2 
    L_0003: call instance void Test.TestFixture/ValueSource::set_Value(string) 
    L_0008: nop 
    L_0009: ret 
} 

ve çoğaltmak:

 [Test] 
    public void Test_with_DynamicMethod() 
    { 
     var sourceType = typeof(ValueSource); 
     PropertyInfo property = sourceType.GetProperty("Value"); 

     var setter = property.GetSetMethod(true); 
     var method = new DynamicMethod("Set" + property.Name, null, new[] { sourceType.MakeByRefType(), typeof(string) }, true); 
     var gen = method.GetILGenerator(); 

     gen.Emit(OpCodes.Ldarg_1); // Load input to stack 
     gen.Emit(OpCodes.Ldarg_2); // Load value to stack 
     gen.Emit(OpCodes.Call, setter); // Call the setter method 
     gen.Emit(OpCodes.Ret); 

     var result = (SetValueDelegate)method.CreateDelegate(typeof(SetValueDelegate)); 

     var source = new ValueSource(); 

     result(ref source, "hello"); 

     source.Value.ShouldEqual("hello"); 
    } 

    public delegate void SetValueDelegate(ref ValueSource source, string value); 

"İşlem çalışma zamanını istikrarsızlaştırabilir" istisnası var. IL, benimle aynı fikirde görünüyor, herhangi bir fikir? ValueSource bir değer türüdür, bu yüzden burada bir ref parametresi yapıyorum. Dinamik yöntem öyle görünüyor çünkü

gen.Emit(OpCodes.Ldarg_0); // Load input to stack 
    gen.Emit(OpCodes.Ldarg_1); // Load value to stack 

:

 public struct ValueSource 
    { 
     public string Value { get; set; } 
    } 
+0

(umarım basit) ValueSource olma şansı yüzden üretebilir ...? –

+1

Ayrıca - değer türleri gerçekten değişmez olmalı, bu moot yapardı ... –

cevap

4

Değişim 0/1 (değil 1/2) için args: DÜZENLEME

İşte ValueSource tip

Statik olarak oluşturulmalıdır, örneğin (orjinal yöntem örneğinizdir) - dolayısıyla args birer birer kapalıdır.

(orijinal yanlış cevap için üzgünüm - Eğer true olarak kodun diğer bit bırakabilirsiniz)

+0

Evet, öyleydi. Bir dahaki sefere şablon yöntemimi statik hale getireceğim. –

İlgili konular