我想要一个类似于 string.Contains
的行为界面假设有一个类代表 RabbitMq 标签之类的东西。说有'1.222.3331.1'
并在上面写着.Contains(
122 )
得到 false 和 .Contains(
1 )
成为现实。
我尝试过:
interface ITag
{
bool Contains(ITag tag);
}
但其实现会限制 Contains
与 ITag
一起工作给出类似的东西:
class Tag : ITag
{
public bool Contains(ITag tag)
{
throw new NotImplementedException();
}
}
虽然我想要例如:
class Tag : ITag
{
public string s;
public bool Contains(Tag other)
{
return s.Contains(other.s);
}
}
我想知道我所描述的可实现接口(interface)以及如何实现,是否有任何现成的.Net接口(interface)可以.Contains
?
我当然可以
interface ITag<T>
{
bool Contains(T tag);
}
然后用类似的东西来实现它:
class Tag : ITag<Tag>
{
public Tag(string tag)
{
Content = tag;
}
public string Content { get; private set; }
public bool Contains(Tag other)
{
return other != null
&& other.Content != null
&& Content.Contains(other.Content);
}
}
但是我需要制作所有使用 ITag<T>
的界面通用,这是不希望的。有没有非通用的方法?
最佳答案
将编译以下内容:
interface ITag<in TTag> where TTag : ITag<TTag>
{
bool Contains(TTag tag);
}
class Tag : ITag<Tag>
{
public bool Contains(Tag t)
{
return false;
}
}
也就是说,与仅使用具体类型相比,整个构造并不是很有用,因为您始终需要将其包含在变量声明中。
关于c# - 如何描述一个以 bool Contains(T) 方法作为接口(interface)的 T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733095/