因此,如果我嘗試調用類型爲IList的類的屬性上的「清除」,則會引發它。如果我在IList類型的常量上做同樣的事情,程序運行良好。在接口IList上的Expression.PropertyOrField上的Expression.Call <T>引發InvalidOperationException
class Program
{
static void Main(string[] args)
{
var parent = new Parent(new List<SomeClass>());
parent.Data.Add(new SomeClass("Test"));
Console.WriteLine(parent.Data.Count);
var expr = Expression.Lambda(Expression.Call(Expression.Constant(parent.Data), "Clear", null, null), null);
var x = expr.Compile();
x.DynamicInvoke();
Console.WriteLine(parent.Data.Count);
var expr2 = Expression.Lambda(Expression.Call(Expression.PropertyOrField(Expression.Constant(parent), "Data"), "Clear", null, null), null);
var x2 = expr.Compile();
x2.DynamicInvoke();
Console.WriteLine(parent.Data.Count);
Console.ReadLine();
}
public class Parent
{
public Parent(IList<SomeClass> data)
{
this.Data = data;
}
public IList<SomeClass> Data { get; set; }
}
public class SomeClass
{
public SomeClass(string value) { }
}
}
// output:
// 1
// 0
// Exception of type: InvalidOperationException was thrown
這只是一個bug還是有它這樣做