C# 运算符重载和 implicit关键字
运算符重载是指允许用户使用用户定义的类型编写表达式的能力。它允许用户定义的类型与预定义的类型具有相同的功能。
implicit 关键字用于声明隐式的用户定义类型转换运算符。如果转换过程可以确保不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换。
public class Student
{
public Student()
{
}
public Student(string name)
{
this.Name = name;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public static Student operator &(Student s1, Student s2)
{
Student st = new Student();
st.Age = s1.Age + s2.Age;
return st;
}
public static implicit operator Student(string name)
{
return new Student(name);
}
class Program
{
static void Main(string[] args)
{
Student s1 = new Student() { Name = "wang", Age = 11 };
Student s2 = new Student() { Name = "Li", Age = 13 };
Student st = s1 & s2;
Console.WriteLine(st.Age);
Fun("wanglijiang");
}
static void Fun(Student st)
{
Console.WriteLine(st.Name);
}
{
public Student()
{
}
public Student(string name)
{
this.Name = name;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public static Student operator &(Student s1, Student s2)
{
Student st = new Student();
st.Age = s1.Age + s2.Age;
return st;
}
public static implicit operator Student(string name)
{
return new Student(name);
}
class Program
{
static void Main(string[] args)
{
Student s1 = new Student() { Name = "wang", Age = 11 };
Student s2 = new Student() { Name = "Li", Age = 13 };
Student st = s1 & s2;
Console.WriteLine(st.Age);
Fun("wanglijiang");
}
static void Fun(Student st)
{
Console.WriteLine(st.Name);
}
}
作 者:
出 处:
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面 明显位置给出原文连接,否则保留追究法律责任的权利。