,如果我有: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