私が持っている場合:
public static Func<SomeType, bool> GetQuery() {
return a => a.Foo=="Bar";
}
そしてジェネリックバージョン
public static Func<T, bool> GetQuery<T>() {
return (Func<T,bool>)GetQuery();
}
強く型付けされた Func of SomeType を Func of T にキャストする方法はありますか? これまでに見つけた唯一の方法は、それをモック関数と組み合わせることです。
Func<T, bool> q=a => true;
return (Func<T, bool>)Delegate.Combine(GetQuery(), q);
Expression.Lambda でそれを行う方法は知っていますが、式ツリーではなく、単純な関数を使用する必要があります
EDIT - .net 3.5 Using 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
}
}