0

我不太了解属性。代码行:method2(x.str1, x.str2, x.str3, x.str4); --- 向我抛出“对象引用未设置为对象错误的实例”。任何想法表示赞赏。x.str1 没有解决?

(我正在添加一些代码并向现有设置添加更多功能。我会使用方法和属性初始化类 myProperty。)

使用其他C#

   class Test{

    private myProperty x;

    private string  str1, str2, str3, str4;

    private myProperty A
            {

                get { return x; }          

                set
                {

                    str1 = value.str1;
                    str2 = value.str2;
                    str3 = value.str3;
                    str4 = value.str4;

                }             
            }

    public void myMethod()
        {

               Test tst = new Test();
               myProperty x = new myProperty();
               //Assigning property varaibles:
                  x.str1 = "this";
                  x.str2 = "is";
                  x.str3 = "my";
                  x.str4 = "test";

               try
                {

                    tst.method2(x.str1, x.str2, x.str3, x.str4);
                }
                catch(Exception)
                {
                    throw;
                }
            }

    public void method2(string str1, string str2,string str3, string str4)
     {
     }

    }

    OtherC#.cs  contains the definition for myProerty class

    namespace temp
    {
    public class xyx {some code;}
    public interface abc {some code};
    public class myProperty {

            public string str1 { get; set; }

            public string str2 { get; set; }

            public string str3 { get; set; }

            public string str4 { get; set; }
    }
    }
4

2 回答 2

5

myProperty x调用时未设置为对象的实例

x.str1 = "this";

您必须首先初始化它(例如,在您的构造函数代码中)。

于 2012-05-18T18:02:28.293 回答
3

变量只是对对象的引用。它本身并不是一个对象。因此,在您将其设置为引用对象之前,该变量为空。在这种情况下,您可能只是希望它等于一个新对象,因此您需要实例化一个。例如,更改此行:

private myProperty x;

对此:

private myProperty x = new myProperty();

我应该澄清这仅适用于引用类型(类),而不是值类型(结构)。

于 2012-05-18T18:03:18.653 回答