C# 类不实现接口,代码仍在编译
我需要创建一个实现IBindingList的自定义集合,以便能够将其与来自第三方的自定义控件绑定。我遇到的另一个问题是,我必须使集合线程安全,因为我同时从多个线程手动插入项目 无论如何,我在我的类中使用了一个C# 类不实现接口,代码仍在编译,c#,interface,C#,Interface,我需要创建一个实现IBindingList的自定义集合,以便能够将其与来自第三方的自定义控件绑定。我遇到的另一个问题是,我必须使集合线程安全,因为我同时从多个线程手动插入项目 无论如何,我在我的类中使用了一个BindingList字段,这样就不会对轮子进行太多的改造。所以我的班级看起来像: class ThreadSaveBindingCollection<T> : IEnumerable<T>, IBindingList { BindingList<T&g
BindingList
字段,这样就不会对轮子进行太多的改造。所以我的班级看起来像:
class ThreadSaveBindingCollection<T> : IEnumerable<T>, IBindingList
{
BindingList<T> collection;
object _lock = new object();
// constructors
public ThreadSaveBindingCollection(IEnumerable<T> initialCollection)
{
if (initialCollection == null)
collection = new BindingList<T>();
else
collection = new BindingList<T>(new List<T>(initialCollection));
}
public ThreadSaveBindingCollection() : this(null)
{
}
// Todo: Implement interfaces using collection to do the work
}
class ThreadSaveBindingCollection:IEnumerable,IBindingList
{
绑定列表集合;
对象_lock=新对象();
//建设者
公共ThreadSaveBindingCollection(IEnumerable initialCollection)
{
if(initialCollection==null)
collection=newbindingslist();
其他的
collection=newbindingslist(newlist(initialCollection));
}
public ThreadSaveBindingCollection():此(null)
{
}
//Todo:使用集合实现接口以完成工作
}
注意,我没有实现接口IEnumerable和IBinding列表我计划让field集合
在实现这些接口时解决这个问题。因此,我让visual studio显式实现该接口,并用字段集合实现替换抛出新的NotImplementedException()
,最终得到如下结果:
现在的问题是
如果集合声明实现IBindingList!,为什么我不能在字段集合上调用AddIndex方法强>
我无法对几种方法执行相同的操作它是通过绑定列表
明确实现的,您需要将集合
的引用转换为IBindingList
才能使用它:
(collection as IBindingList).AddIndex(property);
通过接口本身的引用进行显式实现和访问的目的是解决命名冲突,当双方使用相同的方法签名创建两个单独的接口时,它允许您在仍然实现两个接口的同时消除方法的歧义。通过BindingList
,您需要将collection
的引用转换为IBindingList
才能使用它:
(collection as IBindingList).AddIndex(property);
通过接口本身的引用进行显式实现和访问的目的是解决命名冲突,当双方使用相同的方法签名创建两个单独的接口时,它允许您在仍然实现两个接口的同时消除方法的歧义。这是因为它是接口,而不是隐式的。这意味着您必须通过接口而不是类型本身来调用它。例如:
((IBindingList)collection).AddIndex(property);
有关显式接口实现的更多信息,请参阅。这是因为它是接口的显式实现,而不是隐式实现。这意味着您必须通过接口而不是类型本身来调用它。例如:
((IBindingList)collection).AddIndex(property);
有关显式接口实现的更多信息,请参阅。BindingList
显式实现IBindingList
,因此您需要执行以下操作
(collection as IBindingList).AddIndex(property);
BindingList
显式实现了IBindingList
,因此您需要
(collection as IBindingList).AddIndex(property);
看起来您的第二个代码块丢失了。你能确定所有相关的代码都在你的问题中吗?转换到IBindingList,然后调用。看起来你的第二个代码块丢失了。你能确定所有相关的代码都在你的问题中吗?转换到IBindingList,然后打电话。