कोई इसStruct v/s कक्षा सी में # - कृपया विस्तार से बताएं व्यवहार
class testCompile
{
/*
* Sample Code For Purpose of Illustration
*/
struct person
{
public int age;
public string name;
}
static void Main(string[] args)
{
List<person> Listperson = new List<person>();
person myperson = new person();
for (int i = 1; i <= 2; i++)
{
//Assignment
myperson.age = 22+i;
myperson.name = "Person - " + i.ToString();
Listperson.Add(myperson);
}
int x = 0;
while (x < Listperson.Count)
{
//Output values
Console.WriteLine("{0} - {1}", Listperson[x].name, Listperson[x].age);
x++;
}
}
}
/*
Output:
Person - 1 - 23
Person - 2 - 24
*/
के व्यवहार क्यों मैं एक struct के रूप में एक वर्ग के लिए एक ही उत्पादन हो रही है नहीं कर रहा हूँ कृपया समझा सकते हैं?
class testCompile
{
/*
* Sample Code For Purpose of Illustration
*/
class person
{
public int age;
public string name;
}
static void Main(string[] args)
{
List<person> Listperson = new List<person>();
person myperson = new person();
for (int i = 1; i <= 2; i++)
{
//Assignment
myperson.age = 22+i;
myperson.name = "Person - " + i.ToString();
Listperson.Add(myperson);
}
int x = 0;
while (x < Listperson.Count)
{
//Output values
Console.WriteLine("{0} - {1}", Listperson[x].name, Listperson[x].age);
x++;
}
}
}
/*
Output:
Person - 2 - 24
Person - 2 - 24
*/
ऐसा इसलिए है क्योंकि ढेर पर ढांचे के उदाहरण आवंटित किए जाते हैं और कक्षाओं के उदाहरण ढेर पर आवंटित किए जाते हैं। ओह। – jason
@ जेसन: नहीं, इस बारे में बहुत भ्रम है कि मूल्य प्रकार बनाम संदर्भ प्रकार संग्रहीत किए जाते हैं। एरिक के उत्कृष्ट ब्लॉग पोस्ट को पढ़ने के लिए सर्वश्रेष्ठ: http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx –
@ 0xA3: आपका अंदरूनी मजाक उबाऊ हास्य डिटेक्टर विफल – jason