【问题标题】:Generic method calls with generic type checks具有泛型类型检查的泛型方法调用
【发布时间】:2022-01-03 15:39:33
【问题描述】:

我正在尝试概括一些构建器重复方法调用。 我有一些实体并试图实现调用标准方法,如果它们已经实现了一些接口。 这是我试图在代码中实现的目标:

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
{
  ...
}

有没有办法对泛型类型进行类型检查并将其传递给另一个泛型方法?

【问题讨论】:

标签: c# abstraction


【解决方案1】:

你可以做到这一点,使用一些反射魔法,或者,如果你的HandleStandards 有一个T 类型的参数,你可以更容易地做到这一点。所以首先,让我们看看如果builder 的类型是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 });
    }
}

【讨论】:

  • 谢谢!不幸的是,builder 与泛型类型无关。因此,我没有泛型类型参数,并且我的其他处理程序也不是静态的。我会通过反射尝试一下。
  • Here 是我为解决您的问题而设计的示例,如果您需要一些实现细节,请查看
  • 感谢您的解决方案。我在我的情况下对其进行了测试,它奏效了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多