运算符重载是指允许用户使用用户定义的类型编写表达式的能力。它允许用户定义的类型与预定义的类型具有相同的功能。
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);
}
}