我不太瞭解屬性。代碼行:method2(x.str1,x.str2,x.str3,x.str4); ---拋出一個「對象引用未設置爲對象錯誤的實例」。任何想法讚賞。 x.str1不解決?使用c#中的屬性初始化一個類 -
使用
otherC#
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; }
}
}
+1,OP聽起來好像你來自C++,當你聲明它們的時候會自動創建對象。在使用它之前,你需要創建一個新的實例,比如'x = new myProperty()'。 – Tejs
@Tejes您還必須在C++中顯式創建對象。我多年來一直沒有使用C++,但很難想象這會改變......除非我通過某種蠕蟲洞進入另一個宇宙。 –