为对象属性分配静态 [英] assigning static to an object property
本文介绍了为对象属性分配静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么当我执行以下操作时为什么:
Why is it when I do something as follows:
public readonly string _objectString = ExtNameSpace.StaticClass.MyVar;
where MyVar is defined inside the static class StaticClass as
public static readonly string MyVar
我收到以下错误:
非静态字段,方法或属性需要对象引用
我期望这会以相反的方式发生,即如果我将对象变量分配给静态成员变量.
I get the following error:
An object reference is required for the nonstatic field, method, or property
I was expecting this to happen the other way around, ie if I am assigning an object variable to a static member variable.
推荐答案
您只需要了解 instance (非静态)方法有效;这是了解OOP的起点之一.
请参阅我过去的解决方案,在此我会对其进行详细说明:是什么使静态的 [ ^ ].
—SA
You just need to understand how instance (non-static) methods work; which is one of the starting point to get before to understand OOP.
Please see my past solution where I explain it in a pretty detailed manner: What makes static methods accessible?[^].
—SA
我无法在.NET 4.0中重现此行为.您正在使用哪个版本的.NET?
我能想到的唯一会产生错误消息的情况是,如果您尝试使用MyVar现在定义在另一个静态类中的方式(非静态)来定义MyVar.
如果是这种情况,则只需将"MyVar"的声明更改为:
I''m unable to reproduce this behavior in .NET 4.0. Which version of .NET are you using ?
The only scenario I can think of that would produce the error message you report is if you tried to define MyVar the way it is now (non-static) inside another class which is static.
If that''s the case then simply change ''MyVar''s declaration to:
public static readonly string _objectString = ExtNameSpace.StaticClass.MyVar;
如果这不是答案,请在定义变量_objectString的位置显示选择的代码,然后发生在其中的类的声明.
If that''s not an answer, please show a selection of your code at the place where the variable _objectString is defined, and the declaration for the class it occurs in.
这篇关于为对象属性分配静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文