Re: [问题] 接口实作的问题

楼主: name2name2 (yang~hi)   2017-01-15 20:58:11
刚google到这篇
https://msdn.microsoft.com/zh-tw/library/d5x73970.aspx
在Employee的例子中Employee有Name属性,
对于下方的这个泛型类别
public class GenericList<T> where T : Employee
public T Data
{
get { return data; }
set { data = value; }
}
....中略...
while (current != null)
{
//The constraint enables access to the Name property.
if (current.Data.Name == s)
{
t = current.Data;
break;
}
...后略
他底下给的解释是
该条件约束可让泛型类别使用 Employee.Name 属性,
因为型别 T 的所有项目都一定会是 Employee 物件,
或继承自 Employee 的物件。
所以应该 Employee 跟 有继承Employee的类别 都可以被使用or加入
下个例子
class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>,
new()
解释
只要使用 条件约束型别 和 其继承阶层架构内的所有型别,
运算和方法呼叫都会受到支援。
看完理解大概如此
接口的部分刚才试了一下
IB:IA,
IB就算没有宣告IA里的方法,
C : IB 还是需要同时实作IB 和IA里的方法 不然会错
所以没宣告一样要实作 >> 不宣告不影响最终效果
http://i.imgur.com/XsYViel.png
再试了下如果在B重复宣告A里的方法,照看到的提示,
这样做好像是会把A的方法屏蔽掉,所以他建议要加new
但我没加new还是build的过,所以或许不加new效果上没差
http://i.imgur.com/oGC4Eme.png
(有错请告知..)
※ 引述《wwe90425 (撒尿牛丸)》之铭言:
: 之前看深入浅出c#有提到
: 如果有继承接口的话,一定要实作接口的方法或属性
: 但这几天上班看到同事写的程式码时
: 却发现没有实作接口类别理的方法,却可以顺利compile没报错
: 想请问一下这是什么原因?
: 附上程式码:
: 接口:
: public interface IRepository<T> where T : class
: {
: IQueryable<T> GetAll();
: T GetById(int id);
: void Add(T entity);
: void Update(T entity);
: void Delete(T entity);
: void Delete(int id);
: }
: 继承接口的类别:
: public interface IRepoPostSubDtl : IRepository<T_PostSubDtl>
: {
: }
: 另外想请问一下where T : class这是什么意思
: 请高手帮忙解答,感谢~
作者: kalaja (菸酒生)   2017-01-15 21:23:00
https://goo.gl/Kqup0T msdn 有解释这样的情况。不同接口但有相同名称方法,也可实作被屏蔽掉的接口。
作者: CloudyWing (孤单ㄉ翼)   2017-01-18 14:58:00
不加new遇到同名就会默认Hide,加new就是告诉编译器要Hide

Links booklink

Contact Us: admin [ a t ] ucptt.com