“关键字'this'在静态属性,静态方法或静态字段初始值设定项中无效".将方法添加到ExpandoObject时 [英] "Keyword 'this' is not valid in a static property, static method, or static field initializer" when adding methods to an ExpandoObject

查看:94
本文介绍了“关键字'this'在静态属性,静态方法或静态字段初始值设定项中无效".将方法添加到ExpandoObject时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试向ExpandoObject添加动态方法,该方法将向其返回属性(动态添加),但是它总是给我错误.

I am try to add a dynamic method to ExpandoObject which would return the properties (added dynamically) to it, however it's always giving me error.

我在这里做错什么了吗?

Is something wrong I am doing here?

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

The Compiler is flagging the following error: Error 1

关键字"this"在静态属性,静态方法或静态字段初始化程序

Keyword 'this' is not valid in a static property, static method, or static field initializer

D:\ rnd \ GettingStarted \ DynamicDemo \ ExpandoFun.cs 20 63 DynamicDemo

D:\rnd\GettingStarted\DynamicDemo\ExpandoFun.cs 20 63 DynamicDemo

推荐答案

好,您在lambda中使用了 this ,它将引用创建 Action .您不能这样做,因为您使用的是静态方法.

Well, you're using this in the lambda, which would refer to the object that is creating the Action. You cannot do that because you're in a static method.

即使您处于实例方法中,它也不能与 this 一起使用,因为它将引用创建 Action 的对象的实例,而不是>将ExpandoObject 塞入其中.

Even if you were in an instance method, it would not work with this because it would refer to the instance of the object creating the Action, not the ExpandoObject where you're tucking it.

您需要引用ExpandoObject(学生):

You need to reference the ExpandoObject (student):

student.Introduction=new Action(()=>
    Console.WriteLine("Hello my name is {0} {1}",student.FirstName,student.LastName);
);

这篇关于“关键字'this'在静态属性,静态方法或静态字段初始值设定项中无效".将方法添加到ExpandoObject时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆