C#访问静态函数中的非静态成员 [英] C# accesing non static member in a static function

查看:39
本文介绍了C#访问静态函数中的非静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个函数:

List<string> names = new string();

private static void getName(string name)
{
    names.add(name);
}

当我尝试编译时,我得到一个:非静态字段需要对象引用"通知.我该怎么做才能使这个成员(名称)与 getName 兼容?

When I attempt to compile I get a: 'object reference is required for the non-static field' notice. What do I have to do to make this member (names) compatible with getName?

我需要它是非静态的或转换的,因为我想将结果放入其他非静态函数和表单中.

I need it to be non static or converted because I want to put the results into other non static functions and forms.

推荐答案

你需要告诉系统哪个你感兴趣的名字列表.它是一个对象状态的一部分,一个类的实例......但哪个?也许您已经创建了几个 类的实例——也许您已经创建了没有 个类的实例.静态方法没有可见性 - 那么您希望它从哪个实例获取 names 变量值?

You need to tell the system which list of names you're interested in. It's part of the state of an object, an instance of the class... but which one? Maybe you've created several instances of the class - maybe you've created no instances of the class. The static method has no visibility of that - so which instance do you want it to fetch the names variable value from?

换个例子,假设我们有一个这样的类:

To put it in another example, suppose we had a class like this:

public class Person
{
    public double MassInGrams { get; set; }
    public double HeightInMetres { get; set; }

    public static double ComputeBodyMassIndex()
    {
        // Which person are we interested in?
    }
}

Person p1 = new Person { MassInGrams = 76203, HeightInMetres = 1.8 };
Person p2 = new Person { MassInGrams = 65000, HeightInMetres = 1.7 };

double bmi = Person.ComputeBodyMassIndex();

你期望结果是什么?您已经要求 Person 类计算BMI",但没有告诉它要计算 BMI.你需要向它提供这些信息.

What would you expect the result to be? You've asked the Person class to compute "the BMI" but without telling it whose BMI to compute. You need to give it that information.

针对您的情况的一些选项:

Some options for your situation:

  • names改为静态
  • 将方法更改为实例方法
  • 传入一个类的实例
  • 创建一个类的实例,可能会返回它
  • 以其他方式获取类的实例

顺便说一下,对于添加名称的东西来说,这是一个非常奇怪的方法名称.这也有点不合常规...

By the way, that's a very strange method name for something which adds a name. It's also somewhat unconventional...

这篇关于C#访问静态函数中的非静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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