[英]How can I define an interface method whose different implementation can return <T>, List<T>, List<List<T>> where T is a custom class
interface IParser
{
return type parseData(list<byte> data);
}
Where return type can be a T
, List<T>
or List<List<T>>
返回类型可以是T
、 List<T>
或List<List<T>>
Declare your interface like this像这样声明你的界面
interface IParser<T>
{
T ParseData(List<byte> data);
}
Can be used like this:可以这样使用:
public class Parser<T> : IParser<T>
{
public virtual T ParseData(List<byte> data) //virtual is optional
{
//do stuff and return T
//T could be anything, a List, a struct, a class what ever
return default(T);
}
}
If you need a specific parser you could do this:如果你需要一个特定的解析器,你可以这样做:
public class StringParser : Parser<string>
{
public override string ParseData(List<byte> data)
{
return string.Empty;
}
}
Or if you need a specific parser for a collection of T
或者,如果您需要特定的解析器来处理T
的集合
public class CollectionParser<TItem> : Parser<IEnumerable<TItem>>
{
public override IEnumerable<TItem> ParseData(List<byte> data)
{
return Enumerable.Empty<TItem>;
}
}
Something like this:像这样的东西:
public interface IParser<TOut> where TOut : class
{
TOut ParseData(List<byte> data);
}
Since the question was about T as a custom class thereby verify that the type of TOut is class.由于问题是关于 T 作为自定义 class 从而验证 TOut 的类型是 class。 Maybe a good addition would be as following:也许一个很好的补充如下:
public interface IParser<in TIn, out TOut> where TOut : class
{
TOut ParseData(TIn data);
}
and the implementation would be:实施将是:
class Parser : IParser<List<byte>, CustomClass>
{
CustomClass ParseData(List<byte> data)
{
return new CustomClass();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.