我正在进入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 aCoolObj = new MyClass();
aCoolObj.MyCoolStaticMethod();

这是解决方案:

MyClass.MyCoolStaticMethod();

解释:

不能从对象的实例调用静态方法。静态方法的全部意义在于不绑定到对象的实例,而是持久化到该对象的所有实例,并且/或在没有任何对象实例的情况下使用。

其他回答

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

这会导致错误:

MyClass aCoolObj = new MyClass();
aCoolObj.MyCoolStaticMethod();

这是解决方案:

MyClass.MyCoolStaticMethod();

解释:

不能从对象的实例调用静态方法。静态方法的全部意义在于不绑定到对象的实例,而是持久化到该对象的所有实例,并且/或在没有任何对象实例的情况下使用。

不能通过实例引用访问

这意味着您正在调用一个STATIC方法并将一个实例传递给它。最简单的解决方案是删除Static,例如:

ExportToExcel(IEnumerable data, string sheetName) {

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

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

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

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类的任何实例都没有意义。