gpt4 book ai didi

c# - "Keyword ' 这个 ' is not valid in a static property, static method, or static field initializer"向 ExpandoObject 添加方法时

转载 作者:太空狗 更新时间:2023-10-29 17:43:55 27 4
gpt4 key购买 nike

我尝试向 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 动态演示

最佳答案

好吧,您在 lambda 中使用了 this,它将引用创建 Action 的对象。你不能那样做,因为你在静态方法中。

即使您在实例方法中,它也不会与 this 一起使用,因为它会引用创建 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com