结构函数

结构类型不但可以用来存储数据元素,还可以用来包含函数。

举一个例子,

struct CustomerName
{
        public string firstName,lastName;
}

static void Main(string [] args)
{
        CustomerName myCustomer;
    
        myCustomer.firstName = "John";
        myCustomer.lastName = "Franklin"
        WriteLine($"{myCustomer.firstName} {myCustomer.lastName}");

}

这里显然有些繁琐。如果我们使用结构包含函数,语法就会简单很多。

struct CustomerName
{
        public string firstName,lastName;
        public string Name() =>firstName + " "+lastName;
}

static void Main(string [] args)
{
        CustomerName myCustomer;
    
        myCustomer.firstName = "John";
        myCustomer.lastName = "Franklin"
        WriteLine(myCustomer.Name());

}    
posted @ 2020-01-01 21:58  Luohanhui  阅读(313)  评论(0编辑  收藏  举报