如何转换通用的c#动作Action< T2>

本文关键字:动作 T2 T1 Action 何转换 转换 | 更新日期: 2023-09-27 18:01:20

我一直在用c#学习和创造一些东西;不幸的是,我是c#的新手,我在转换方面遇到了一些麻烦。

我有一个Type1的Action,我想把它转换成Type2;这两种类型在编译时都是已知的。以下是我试图存档的示例代码。

public class Example <Resolve, Reject>
{
    protected Resolve resolved;
    protected Reject rejected;
    public Example( Resolve value ) { resolved = value; }
    public Example( Reject value ) { rejected = value;  }
    public void invoke( Action<Resolve> callback ) {
        if( null != resolved ) { callback (resolved ); }
        else if( null != rejected ) {
            // How to cast action from Action <Resolve> to Action <Rejected>
            // and invoke it with the rejected value??
            callback ( rejected );
        }
        else throw new ApplicationException( "Not constructed" );
    }
}
public static void Main (string[] args)
{
    Console.WriteLine ("Start");
    var example1 = new Example <string, System.ArgumentException> ( "Str argument" );
    example1.invoke (msg => {
        // Here the msg is a string ok!
        if (msg is string) { Console.WriteLine (msg); }
        else { Console.WriteLine ("Exception"); }
    });
    var example2 = new Example <string, System.ArgumentException> ( new ArgumentException("An exception") );
    example2.invoke (msg => {
        // Here msg should be an ArgumentException.
        if (msg is string) { Console.WriteLine (msg); }
        else { Console.WriteLine ("Exception"); }
    });

    Console.WriteLine ("Done");
    Console.ReadLine ();
}

我无法控制类型,所以我不能将一个类型转换为另一个类型,即使我可以,我正在实现的规范也要求我必须根据运行时发生的一些条件,使用resolve或Reject值来解析回调。

你能帮我一下吗?

如何转换通用的c#动作<T1>Action< T2>

免责声明:我是以下开源库的作者

如果您使用区分联合类型和模式匹配,如Succinc所提供的,您可以简单地将需要的内容写为:

public static void MessageOrException(Union<string, ArgumentException> value)
{
    value.Match().Case1().Do(Console.WriteLine)
                 .Else(Console.WriteLine("Exception")
                 .Exec();
}

public static void Main (string[] args)
{
    Console.WriteLine ("Start");
    var example1 = new Union<string, ArgumentException> ("Str argument");
    MessageOrException(example1);  // Writes "Str argument"
    var example2 = 
        new Union<string, ArgumentException>(new ArgumentException("An exception"));
    MessageOrException(example2); // Writes "Exception"
    Console.WriteLine ("Done");
    Console.ReadLine ();
}