在结构体内可以定义函数,方便调用
struct CustomerName
{ //注意:定义时 结构体内函数和变量定义都要public
public string firstName;
public string lastName;
public string Fullname()
{
return firstName + lastName;
}
}
class Program
{
static void Main(string[] args)
{
CustomerName myName; //先定义一个结构体
myName.firstName = "Yao";
myName.lastName = "CC";
Console.WriteLine("my name is " + myName.Fullname());
Console.ReadKey();
}
}
例子:求一个三维向量的长度
struct Vector3
{
public float x;
public float y;
public float z;
public double Long()
{
return Math.Sqrt(x * x + y * y + z * z);
}
}
class Program
{
static void Main(string[] args)
{
Vector3 myVector3;
myVector3.x = 4;
myVector3.y = 5;
myVector3.z = 8;
Console.WriteLine(myVector3.Long());
Console.ReadKey();
}
}