相关疑难解决方法(0)

如何使用反射来调用泛型方法?

当在编译时未知类型参数但是在运行时动态获取时,调用泛型方法的最佳方法是什么?

考虑以下示例代码 - 在Example()方法内部,GenericMethod<T>()使用Type存储在myType变量中调用的最简洁方法是什么?

public class Sample
{
    public void Example(string typeName)
    {
        Type myType = FindType(typeName);

        // What goes here to call GenericMethod<T>()?
        GenericMethod<myType>(); // This doesn't work

        // What changes to call StaticMethod<T>()?
        Sample.StaticMethod<myType>(); // This also doesn't work
    }

    public void GenericMethod<T>()
    {
        // ...
    }

    public static void StaticMethod<T>()
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

c# generics reflection

1002
推荐指数
6
解决办法
24万
查看次数

没有使用泛型扩展方法的类型推断

我有以下方法:

public static TEventInvocatorParameters Until
    <TEventInvocatorParameters, TEventArgs>(this TEventInvocatorParameters p,
                                            Func<TEventArgs, bool> breakCond)
    where TEventInvocatorParameters : EventInvocatorParameters<TEventArgs>
    where TEventArgs : EventArgs
{
    p.BreakCondition = breakCond;
    return p;
}
Run Code Online (Sandbox Code Playgroud)

而这堂课

public class EventInvocatorParameters<T>
    where T : EventArgs
{
    public Func<T, bool> BreakCondition { get; set; }
    // Other properties used below omitted for brevity.
}
Run Code Online (Sandbox Code Playgroud)

现在,我有以下问题:

  1. 此扩展方法甚至可以显示所有类型string.
  2. 我不能写new EventInvocatorParameters<EventArgs>(EventABC).Until(e => false);它告诉我"方法的类型参数......不能从用法中推断出来."

我不能使用像这样的泛型类型参数吗?你会如何解决这个问题?
重点:我需要这两个通用参数,因为我需要返回调用此扩展方法的相同类型.


更广泛的图片(没有必要回答问题!):
我正在尝试创建一个流畅的界面来调用事件.基础是这个静态类:

public static class Fire
{
   public static void Event<TEventArgs>(
       ConfiguredEventInvocatorParameters<TEventArgs> parameters)
    where TEventArgs …
Run Code Online (Sandbox Code Playgroud)

.net c# generics extension-methods fluent-interface

12
推荐指数
2
解决办法
2889
查看次数