
public class MyCollection : ICollection<MyType> { private List<MyType> _List = new List<MyType>(); public MyCollection(IEnumerable<MyType> collection) { _List = new List<MyType>(collection); } public static implicit operator MyCollection(IEnumerable<MyType> collection) { return new MyCollection(collection); } // collection methods excluded for brevity public MyCollection Filter(string filter) { return _List.Where(obj => obj.Filter.Equals(filter)); // cannot implicitly convert }} 我之前没有尝试使用隐式用户定义的转换,我做错了什么?
@H_404_6@解决方法 当类型转换为或者类型转换为接口类型时,不允许使用隐式. (如果一种类型是从另一种类型派生出来的话,也不允许使用它们,因为这样的条形对象被允许).实际上,在这种情况下你也不被允许明确.从 ECMA-364第17.9.3节开始:A class or struct is permitted to declare a conversion from a source type
Sto a target typeTonly if all of the following are true,whereS0andT0
are the types that result from removing the trailing?modifIErs,if any,fromSandT:
S0andT0are different types.Either
S0orT0is the class or struct type in which the operator declaration takes place.Neither
S0norT0is an interface-type.Excluding user-defined conversions,a conversion does not exist from
StoTor fromTtoS.
您正在破坏第三个规则(接口类型)和第四个规则(因为存在从MyCollection到IEnumerable< MyType>已经存在的非用户定义的转换).
如果允许的话,无论如何我都会建议不要这样做.
隐式演员表只应在效果非常明显的情况下使用(对于对语言有合理知识的人):在将int转换为long时,x = 3 5的长度非常明显,并且完全明显是什么对象x =“abc”将字符串转换为对象.
除非你使用隐含的类似“明显”的水平,否则这是一个坏主意.
特别是,通常隐式强制转换不应该隐含在相反方向,而应隐含在一个方向(大多数内置情况下的“加宽”方向)和相反方向(“缩小”方向)明确.由于你已经有一个从MyCollection到IEnumerable< MyCollection>的隐式转换,因此在相反的方向上使用隐式转换是一个糟糕的主意.
更一般地说,既然你在谈论使用linq,那么使用可扩展的ToMyCollection()方法会有更大的好处,因为那时你将遵循ToArray(),ToList()等的linq约定:
public static class MyCollectionExtensions{ public static MyCollection ToMyCollection(this IEnumerable<MyType> collection) { return collection as MyCollection ?? new MyCollection(collection); }} 请注意,我测试集合已经是MyCollection的情况,以避免浪费重复的构造.您可能也可能不想处理List< MyType>的情况.特别是在使用内部构造函数时直接将其分配给_List.
但是,在执行此 *** 作之前,您需要考虑允许的别名效果.如果您知道别名不会导致问题,这可能是一个非常有用的技巧(该类仅在内部使用,并且已知别名不是问题,或者别名不会影响MyCollection的使用,或者实际上是别名希望的).如果有疑问,那么只需让方法返回新的MyCollection(集合)更安全.
@H_404_6@ @H_404_6@ 总结以上是内存溢出为你收集整理的c# – 从IEnumerable到MyCollection的隐式转换全部内容,希望文章能够帮你解决c# – 从IEnumerable到MyCollection的隐式转换所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)