Get Parameter Values of Current StackFrame

…みたいな事をやりたかったんですが(・ω・)
リフレクション使って簡単に、っというわけにはいかないか。


パラメータの型と名前ならMethodBaseから取れるわけですが。
ILレベルでシコシコやればどうにかなるかな(゚Д゚)?


で、ログ出力用に簡単にメッセージを作る処理が欲しいというだけの話だったので、こんなものでお茶を濁してみました(´ω`)

TestMethod( con, 1, null, "x", null );

ってカンジで以下の処理を呼ぶと、

public static string TestMethod(OracleConnection con, int a, Nullable<int> b, string x, string y)
{
...

    string calllog =  BuildCallLog( MethodBase.GetCurrentMethod(), con, a, b, x, y );
}

calllogには

TestMethod(OracleConnection con = {Oracle.DataAccess.Client.OracleConnection}, Int32 a = 1, Nullable<Int32> b = null, String x = "x", String y = null)

みたいな文字列が返ってくる処理。
BuildCallLogの中身はこんなん。

public static string BuildCallLog(MethodBase mb, params object[] parameters)
{
    StringBuilder sb = new StringBuilder();

    sb.Append( mb.Name );
    sb.Append( "(" );

    ParameterInfo[] pis = mb.GetParameters();
    for( int index = 0; index < pis.Length; index++ )
    {
        if( ( pis[ index ].ParameterType.IsGenericType ) &&
            ( pis[ index ].ParameterType.GetGenericTypeDefinition().Equals( typeof( Nullable<> ) ) ) )
        {
            PropertyInfo pi = pis[ index ].ParameterType.GetProperty( "Value" );
            Type paramType = pi.PropertyType;
            sb.Append( "Nullable<" );
            sb.Append( paramType.Name );
            sb.Append( ">" );
        }
        else
        {
            sb.Append( pis[ index ].ParameterType.Name );
        }

        sb.Append( " " );

        sb.Append( pis[ index ].Name );

        sb.Append( " = " );

        if( index < parameters.Length )
        {
            if ( parameters[ index ] == null )
            {
                sb.Append( "null" );
            }
            else
            {
                if( parameters[ index ].GetType() == typeof( string ) )
                {
                    sb.Append( "\"" );
                    sb.Append( parameters[ index ].ToString() );
                    sb.Append( "\"" );
                }
                else if( parameters[ index ].GetType().IsValueType )
                {
                    sb.Append( parameters[ index ].ToString() );
                }
                else 
                {
                    sb.Append( "{" );
                    sb.Append( parameters[ index ].ToString() );
                    sb.Append( "}" );
                }
            }
        }
        else
        {
            sb.Append( "???" ); // 引数間違ってるポ(´・ω・`)
        }

        if( index != parameters.Length - 1 )
        {
            sb.Append( ", " );
        }                
    }

    sb.Append( ")" );

    return sb.ToString();
}

でも、異常系に使うんなら例外の詳細でいいんジャないでしょうかね(´ω`)



ひぐらし実写化…エエエェェェ(゜Д゜;)ェェェエエエ