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

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

问题描述

所以我有一个功能:

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.

推荐答案

您需要告诉系统的列表中名字你感兴趣的,它是一个对象,一个类的实例的状态的一部分...但哪一个?也许你已经创建的若干个的类的实例 - 说不定您所创建的之类的没有的实例。静态方法没有的可见性 - 让你想它来获取名称

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();



你会希望得到的结果是什么?你问类来计算的体重指数,但没有告诉它的的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:


  • 更改名称是静态的,而不是

  • 更改方法是一个实例方法

  • 通过在类

  • 的实例创建类的实例,可能它返回

  • 抓取类的一个实例一些其他的方式

  • Change names to be static instead
  • Change the method to be an instance method
  • Pass in an instance of the class
  • Create an instance of the class, possibly returning it
  • Fetch an instance of the class some other way

顺便说一句,这对东西的添加的名称。这也是有点不合常规...

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

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

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