我正在进入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不能通过实例引用访问,而是用类型名限定它

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


当前回答

在这种情况下,不需要使用静态。你也可以在没有GetItem()方法的情况下初始化你的属性,下面是两个例子:

namespace MyNamespace
{
    using System;

    public class MyType
    {
        public string MyProperty { get; set; } = new string();
        public static string MyStatic { get; set; } = "I'm static";
    }
}

消费:

using MyType;

public class Somewhere 
{
    public void Consuming(){

        // through instance of your type
        var myObject = new MyType(); 
        var alpha = myObject.MyProperty;

        // through your type 
        var beta = MyType.MyStatic;
    }
}       

其他回答

在这种情况下,不需要使用静态。你也可以在没有GetItem()方法的情况下初始化你的属性,下面是两个例子:

namespace MyNamespace
{
    using System;

    public class MyType
    {
        public string MyProperty { get; set; } = new string();
        public static string MyStatic { get; set; } = "I'm static";
    }
}

消费:

using MyType;

public class Somewhere 
{
    public void Consuming(){

        // through instance of your type
        var myObject = new MyType(); 
        var alpha = myObject.MyProperty;

        // through your type 
        var beta = MyType.MyStatic;
    }
}       

在c#中,不像VB。NET和Java中,您不能使用实例语法访问静态成员。你应该:

MyClass.MyItem.Property1

来引用该属性或从Property1中删除静态修饰符(这可能是您想要做的)。关于什么是静态的概念,请参阅我的另一个答案。

删除正在尝试调用的函数中的静态。这为我解决了问题。

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

因此,你需要写,

MyClass.MyItem.Property1

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

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

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