我尝试向 ExpandoObject 添加一个动态方法,该方法会返回属性(动态添加)给它,但它总是给我错误。
我在这里做错了吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
namespace DynamicDemo
{
class ExpandoFun
{
public static void Main()
{
Console.WriteLine("Fun with Expandos...");
dynamic student = new ExpandoObject();
student.FirstName = "John";
student.LastName = "Doe";
student.Introduction=new Action(()=>
Console.WriteLine("Hello my name is {0} {1}",this.FirstName,this.LastName);
);
Console.WriteLine(student.FirstName);
student.Introduction();
}
}
}
编译器标记了以下错误:错误 1
Keyword 'this' is not valid in a static property, static method, or static field initializer
D:\rnd\GettingStarted\DynamicDemo\ExpandoFun.cs 20 63 动态演示
1 Câu trả lời
好吧,您在 lambda 中使用了 cái này
,它将引用创建 Action
的对象。你不能那样做,因为你在静态方法中。
即使您在实例方法中,它也不会与 cái này
一起使用,因为它会引用创建 Action
的对象的实例,而不是 >ExpandoObject
您将其塞入的位置。
您需要引用 ExpandoObject(学生):
student.Introduction=new Action(()=>
Console.WriteLine("Hello my name is {0} {1}",student.FirstName,student.LastName);
);
关于c# - "Keyword ' 这个 ' is not valid in a static property, static method, or static field initializer"向 ExpandoObject 添加方法时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4537141/