[英]Extending a method that has a return type
我正在尝试扩展已经具有返回类型的方法。 例如:
IQueryable<int> GetCategoryIds()
所以,我可以使用如下:
IQueryable<int> categories = GetCategoryIds();
我现在正在做:
IQueryable<int> categories = GetCategoryIds().Select(c => new Client() { ClientId == c.clientId });
这有效,但我不想做那个Select
语句。 我宁愿做一个超出type
的扩展方法,所以我可以在扩展方法中使用Reflection来确定类型等并返回结果。 扩展方法类似于:
public static IQueryable<T> LovelyExtension(this T objectType, int clientId)
然后我可以使用这个扩展(希望如此):
IQueryable<int> categories = GetCategoryIds().LovelyExtension<int>(1);
这可能吗? 当我尝试它时,我收到一个错误,因为GetCategoryIds
返回类型与扩展方法不同。 但是,这适用于Select
语句。
您不需要在Type
上编写扩展名(您的示例也没有这样做)。 您需要IQueryable<T>
的扩展名。 你可以这样做:
public static IQueryable<T> LovelyExtension<T>(this IQueryable<T> input, int clientId) {
Type inputType = typeof(T);
// Here you can use reflection if you need to: inputType corresponds to the type of T
// Create an instance of IQueryable<T>, and return it to the caller.
}
更改您的签名,
public static IQueryable<T> LovelyExtension(this T objectType, int clientId)
至
public static T LovelyExtension(this T objectType, int clientId)
要么
public static IQueryable<T> LovelyExtension(this IQuerable<T> objectType, int clientId)
GetCategoryIds()返回一个IQuerable(这是你传递给LovelyExtension的objectType,你的返回类型基于你的原始签名变成IQuerable>,这显然不符合你所追求的。
我相信您需要在客户端类上声明一个接口,并在扩展方法中添加一个constratint。 看一下这篇帖子的通用扩展方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.