【发布时间】:2010-03-15 18:44:50
【问题描述】:
如果我有:
public static Func<SomeType, bool> GetQuery() {
return a => a.Foo=="Bar";
}
还有一个通用版本
public static Func<T, bool> GetQuery<T>() {
return (Func<T,bool>)GetQuery();
}
有没有办法将 SomeType 的强类型 Func 转换为 T 的 Func? 到目前为止我发现的唯一方法是尝试将它与模拟函数结合起来:
Func<T, bool> q=a => true;
return (Func<T, bool>)Delegate.Combine(GetQuery(), q);
我知道如何使用 Expression.Lambda,但我需要使用普通函数,而不是表达式树
编辑 - 使用 .net 3.5 使用 Matthews 示例,并附有明确的使用细节。
我仍然追求的是在返回值时如何从 Func Of concreteType 到 Func Of T。
我只是想克服编译器错误 - 并且很高兴 T 有可能成为不同的类型并引发运行时错误。
public interface ISecureEntity {
Func<T,bool> SecureFunction<T>(UserAccount user);
}
public class Product : ISecureEntity {
public Func<T,bool> SecureFunction<T>(UserAccount user) {
return (Func<T,bool>)SecureFunction(user); //this is an invalid cast
}
public static Func<Product,bool> SecureFunction(UserAccount user) {
return f => f.OwnerId==user.AccountId;
}
public string Name { get;set; }
public string OwnerId { get;set; }
}
public class ProductDetail : ISecureEntity {
public Func<T,bool> SecureFunction<T>(UserAccount user) {
return (Func<T,bool>)SecureFunction(user); //this is an invalid cast
}
public static Func<ProductDetail,bool> SecureFunction(UserAccount user) {
return pd => Product.SecureFunction(user)(pd.ParentProduct);
}
public int DetailId { get;set; }
public string DetailText { get;set; }
public Product ParentProduct { get;set; }
}
然后在存储库中消费:
public IList<T> GetData<T>() {
IList<T> data=null;
Func<T,bool> query=GetSecurityQuery<T>();
using(var context=new Context()) {
var d=context.GetGenericEntitySet<T>().Where(query);
data=d.ToList();
}
return data;
}
private Func<T,bool> GetSecurityQuery<T>() where T : new() {
var instanceOfT = new T();
if (typeof(Entities.ISecuredEntity).IsAssignableFrom(typeof(T))) {
return ((Entities.ISecuredEntity)instanceOfT).SecurityQuery<T>(GetCurrentUser());
}
return a => true; //returning a dummy query
}
}
【问题讨论】:
-
很遗憾,我不明白你想要完成什么。
-
.Net 的哪个版本?这在这里相当重要。
-
已在上面更新以更清晰。使用 .net 3.5 尝试将 Func
转换为 Func 在运行时 T 将是 SomeType 类型,但我想要一个声明:Func GetQuery 的接口(); -
你为什么不给我们一个使用例子,而不是试图找到一些方法不起作用(在你的例子中,T 的唯一有效输入是 Foo。如果你用
Doo() as Func<T, bool>它会编译...但它仍然只能与 Foo 一起使用。 -
希望额外的细节能更好地解释 - 我试图让事情保持抽象以避免对实现造成混淆 - 但显然情况并非如此,只会造成更多的混乱。
标签: c# lambda anonymous-delegates