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

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


当前回答

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

其他回答

不能通过实例引用访问

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

ExportToExcel(IEnumerable data, string sheetName) {

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

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

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

在这种情况下,不需要使用静态。你也可以在没有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;
    }
}       

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

因此,你需要写,

MyClass.MyItem.Property1

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

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