如何检查一个类是否以任何方式实现了泛型接口?
我有以下内容:
public class SomeQueryObject : IQueryObject<SomeQueryDto>
{
public SomeQueryDto query { get; set; } = new SomeQueryDto();
}
public class SomeQueryDto : BaseQueryDto
{
// some properties
}
public class BaseQueryDto
{
// some properties
}
public interface IQueryObject<T> where T : BaseQueryDto
{
T query { get; set; }
}
有没有办法使用这个接口来检查一个参数是否实现了通用接口而不提供 T? 传递基类不匹配,使用 SomeQueryDto 类会失败
private static string BuildQueryObjectString<T>(T dto)
where T : IQueryObject<?>
{
//use query field in method body
dto.query= foo;
}
我可以更改接口以实现另一个非通用接口并检查它,但是类可以只使用它而根本没有通用接口:
public interface IQueryObject<T> : IQueryObject where T : BaseQueryDto
{
T query { get; set; }
}
public interface IQueryObject { }
public class SomeQueryObject : IQueryObject
{
// no query field
}
private static string BuildQueryObjectString<T>(T dto)
where T : IQueryObject // kind of pointless, the above class would pass this check but doesn't implement the field
{
//method body, no access to query field
dto.query= foo; // error
}