如何将通用C#Action <t1>转换为Action <t2>

时间:2015-07-06 19:53:27

标签: c# generics casting delegates

我一直在用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值来解决回调问题。在运行期间发生的某些情况。

你可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

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

如果你使用Succinc<T>所提供的有区别的联合类型和模式匹配,你可以简单地在这里写下你需要的东西:

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 ();
}