,如果我有:Func键<sometype。这时候,布尔>到Func键<T,bool>
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<T, bool> q=a => true;
return (Func<T, bool>)Delegate.Combine(GetQuery(), q);
我知道该怎么做,与Expression.Lambda,但我需要用普通的功能,而不是表达式树工作
编辑 - 使用.net 3.5 使用马修斯的例子,并用明确的细节。
我仍然是什么后,我怎么能返回一个值从Func的concreteType到Func的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
}
}
不幸的是,我不明白你要完成的任务。 – 2010-03-15 18:48:47
哪个版本的.Net?这在这里相当重要。 – Dykam 2010-03-15 19:08:16
已经更新,以便更清晰。 使用.NET 3.5 试图铸造Func键到函数求 在运行时T将类型SOMETYPE的,但我想有声明了一个接口: Func键 GetQuery (); –
steve
2010-03-16 13:59:50