我正在进入c#,我有这个问题:

namespace MyDataLayer
{
    namespace Section1
    {
        public class MyClass
        {
            public class MyItem
            {
                public static string Property1{ get; set; }
            }
            public static MyItem GetItem()
            {
                MyItem theItem = new MyItem();
                theItem.Property1 = "MyValue";
                return theItem;
            }
        }
     }
 }

我在UserControl上有这样的代码:

using MyDataLayer.Section1;

public class MyClass
{
    protected void MyMethod
    {
        MyClass.MyItem oItem = new MyClass.MyItem();
        oItem = MyClass.GetItem();
        someLiteral.Text = oItem.Property1;
    }
}

一切正常,除了访问Property1。智能感知只给我“等于,GetHashCode, GetType,和ToString”作为选项。当我把鼠标移到oItem上时。Property1, Visual Studio给我这样的解释:

MemberMyDataLayer.Section1.MyClass.MyItem.Property1。get不能通过实例引用访问,而是用类型名限定它

我不确定这是什么意思,我用谷歌搜索了一下,但没能弄明白。


当前回答

只能使用类型名访问静态成员。

因此,你需要写,

MyClass.MyItem.Property1

或者(这可能是您需要做的)通过从Property1的定义中删除static关键字来使其成为实例属性。

静态属性在类的所有实例之间共享,因此它们只有一个值。根据它现在的定义方式,创建MyItem类的任何实例都没有意义。

其他回答

我也遇到过同样的问题——尽管几年后,有些人可能会发现一些有用的建议:

不要无缘无故地使用“静态”!

理解“静态”在运行时和编译时语义(行为)和语法方面的含义。

A static entity will be automatically constructed some time before its first use. A static entity has one storage location allocated, and that is shared by all who access that entity. A static entity can only be accessed through its type name, not through an instance of that type. A static method does not have an implicit ‘this’ argument, as does an instance method. (And therefore a static method has less execution overhead – one reason to use them.) Think about thread safety when using static entities.

MSDN中关于静态的一些细节:

c#中的静态类 c#中的静态构造函数

只能使用类型名访问静态成员。

因此,你需要写,

MyClass.MyItem.Property1

或者(这可能是您需要做的)通过从Property1的定义中删除static关键字来使其成为实例属性。

静态属性在类的所有实例之间共享,因此它们只有一个值。根据它现在的定义方式,创建MyItem类的任何实例都没有意义。

我知道这是一个老帖子,但我刚刚花了3个小时试图弄清楚我的问题是什么。我通常知道这个错误意味着什么,但您也可以以更微妙的方式遇到这个错误。我的问题是我的客户端类(从实例类调用静态方法的类)具有不同类型的属性,但命名与静态方法相同。编译器报告的错误与这里报告的错误相同,但问题基本上是名称冲突。

对于其他遇到此错误且以上方法都没有帮助的人,请尝试使用命名空间名称.. .()完全限定实例类,以便编译器可以看到您的确切名称。

我在这里谷歌c#编译器错误CS0176,通过(重复)问题静态成员实例引用问题。

在我的例子中,发生错误是因为我有一个同名的静态方法和一个扩展方法。为此,请参见同名静态方法和扩展方法。

[也许这应该是一个评论。对不起,我的名声还不够好。

YourClassName.YourStaticFieldName

你的静态字段看起来像这样:

public class StaticExample 
{
   public static double Pi = 3.14;
}

从另一个类,你可以访问静态字段如下:

    class Program
    {
     static void Main(string[] args)
     {
         double radius = 6;
         double areaOfCircle = 0;

         areaOfCircle = StaticExample.Pi * radius * radius;
         Console.WriteLine("Area = "+areaOfCircle);

         Console.ReadKey();
     }
  }