这里定义了一个接口,在Person类中实现这个方法
interface Compare
{
int CompareTo(object other);
}
public class Person : Compare
{
public int Age { get; set; }
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
Person otherPerson = (Person)value;
if (this.Age < otherPerson.Age)
{
return -1;
}
else if (this.Age > otherPerson.Age)
{
return 1;
}
else
{
return 0;
} } }在这里调用这个接口
static void Main(string[] args)
{
Person p1 = new Person();
Person p2 = new Person(); p1.Age = 100;
p2.Age = 15; if (p1.CompareTo(p2)>0)
{
Console.WriteLine("p1比p2大"); }
else if (p1.CompareTo(p2) <0)
{
Console.WriteLine("p1比p2小");
}
else
{
Console.WriteLine("p1.p2一样大");
}
Console.Read();
}
问题1:p1和p2是如何把值传过去的,传给了谁,经过比较之后把值又如何返回,返回给了谁?问题2:如果在Main中不给p1,p2进行赋值,就会返回"p1.p2一样大",想让他返回“请复制”,该如何操作?小白学习中,请大佬多帮助
interface Compare
{
int CompareTo(object other);
}
public class Person : Compare
{
public int Age { get; set; }
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
Person otherPerson = (Person)value;
if (this.Age < otherPerson.Age)
{
return -1;
}
else if (this.Age > otherPerson.Age)
{
return 1;
}
else
{
return 0;
} } }在这里调用这个接口
static void Main(string[] args)
{
Person p1 = new Person();
Person p2 = new Person(); p1.Age = 100;
p2.Age = 15; if (p1.CompareTo(p2)>0)
{
Console.WriteLine("p1比p2大"); }
else if (p1.CompareTo(p2) <0)
{
Console.WriteLine("p1比p2小");
}
else
{
Console.WriteLine("p1.p2一样大");
}
Console.Read();
}
问题1:p1和p2是如何把值传过去的,传给了谁,经过比较之后把值又如何返回,返回给了谁?问题2:如果在Main中不给p1,p2进行赋值,就会返回"p1.p2一样大",想让他返回“请复制”,该如何操作?小白学习中,请大佬多帮助
解决方案 »
- Keys位运算疑问。
- 子窗口控制父窗口的菜单控件的可用性
- 好好的不知道怎么出现“同时定义了 DataSource 和 DataSourceID”
- 在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式
- GridView中类似与DataGrid中VirtualItemCount的属性是什么
- 如何进行有效的数据库连接测试?
- C#如何做符号重载
- 无效密钥号码
- c/s结构,c端船大量的数据给s端,让s端更新数据库。用sokect合适吗?
- 不知能不能用.net做工业实时B/S项目?
- c# 建一个浏览器,抓包到浏览器接收到的数据,这样的爬虫是不是就不用处理接口加密问题了
- 急:vs2017 c#,using Google.ProtocolBuffers 引用不了
问题1:p1和p2是person类的对象,p1.Age = 100;就是对这个public int Age { get; set; }属性进行赋值。 if (p1.CompareTo(p2)>0)这里p1.CompareTo()就是调用person类继承的接口的CompareTo()功能,因为这个功能参数是object类型,所以p2作为对象参数传过去,传到哪里?传到Person类里的public int CompareTo(object value){}这个方法,然后value就是p2,接着你Person otherPerson =(Person)value;自然otherPerson就是p2了,最后你进行判断if (this.Age < otherPerson.Age){},其中this就是当前的if (p1.CompareTo(p2)>0)中的p1,所以你会判断p1.Age和p2.Age谁大。
问题2:思路看能否自理
在public int CompareTo(object value)
里面可以判断
if (value == null)
{
Console.WriteLine("请赋值");
return;
}
if (!(value is Person))
{
Console.WriteLine("p2不是合法的person");
return;
}