我試圖概括一些構建器重復方法呼叫。我有一些物體并試圖實作呼叫標準方法,如果它們已經實作了一些介面。這是我試圖在代碼中實作的目標:
void MainMethod(){
...
HandleStandards<MyClass>(builder);
...
}
void HandleStandards<T>(..builder..) where T: class, IEntity
{
// of course my problem is with here. because T is not suitable to pass to other methods
if(T is IIdentifiable){
HandleIdentifiable<T>(builder);
}
if(T is ITrackable){
HandleTrackable<T>(builder);
}
}
void HandleIdentifiable<T>(..builder..) where T: class, IEntity, IIdentifiable
{
...
}
void HandleTrackable<T>(..builder..) where T: class, IEntity, ITrackable
{
...
}
有沒有辦法對泛型型別進行型別檢查并將其傳遞給另一個泛型方法?
uj5u.com熱心網友回復:
你可以使用一些反射魔法來做到這一點,或者,如果你HandleStandards有一個型別的引數,T你就可以更容易地做到這一點。所以首先,讓我們看看如果builder是 type怎么辦T:
void HandleStandards<T>(T builder) where T: class, IEntity
{
if (builder is IIdentifiable identifiable)
{
HandleIdentifiable(identifiable)
}
// You'd go on like this
}
如果你沒有型別的引數,T我們將不得不使用一些反射魔法來做到這一點,但這不是很多,這里是:
void Handle Standards<T>() where T : class, IEntity
{
if (typeof(T).IsAssignableTo(typeof(IIdentifiable)))
{
// You'll probably have to use some BindingFlags
// Here I'm assuming that 'HandleIdentifiable' is private and static
// https://docs.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=net-6.0
var method = typeof(TypeContainingTheseMethods).GetMethod(
nameof(HandleIdentifiable),
BindingFlags.NonPublic | BindingFlags.Static
);
// If the method is *not* static, you'll need to pass the instance
// on which to call the method on as the first parameter instead of null
// Plus any additional parameters you may have inside the object array
// in the same order as the method declares them
method.MakeGenericMethod(typeof(IIdentifiable))
.Invoke(null, new object[] { builder });
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/365685.html
下一篇:如何根據索引比較兩個串列
