在C#中,我们无法将值直接分配给结构中的结构成员,例如:
struct Student
{
int roll_number = 101; //Error
string name = "Shaurya"; //Error
}我们也不能使用参数少的构造函数来初始化结构的成员。我们可以使用参数构造函数来初始化成员。
示例
using System;
using System.Collections;
namespace ConsoleApplication1
{
struct Student
{
public int roll_number;
public string name;
public Student( int x, string s)
{
roll_number = x;
name = s;
}
public void printValue()
{
Console.WriteLine("Roll Number: " + roll_number);
Console.WriteLine("Name: " + name);
}
}
class Program
{
static void Main()
{
Student S1 = new Student(101,"Shaurya Pratap Singh");
Student S2 = new Student(102,"Pandit Ram Sharma");
S1.printValue();
S2.printValue();
}
}
}输出结果
Roll Number: 101 Name: Shaurya Pratap Singh Roll Number: 102 Name: Pandit Ram Sharma