1. ホーム
  2. c#

[解決済み] メンバー '<メンバー名>' にインスタンス参照でアクセスできない

2022-02-28 07:12:39

質問

私は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 . インテリセンスでは、" が表示されるだけです。 Equals , GetHashCode , GetType および ToString をオプションで指定します。をマウスオーバーすると oItem.Property1 Visual Studioでは、このように説明されています。

Member MyDataLayer.Section1.MyClass.MyItem.Property1.getを取得します。 cannot be accessed with an instance reference, qualify it with a type name instead

この意味がよくわからず、ググってみたのですがわかりませんでした。

どのように解決するのですか?

C#では、VB.NETやJavaとは異なり、アクセスする際に static のメンバをインスタンス構文で使用します。する必要があります。

MyClass.MyItem.Property1

を使用してそのプロパティを参照するか、または static 修飾子を Property1 (これはおそらくあなたがやりたいことです)。概念的には static は、私の他の回答 .