c#中的泛型和访问T的静态成员

nik*_*sfi 13 c# generics methods static data-access

我的问题涉及到c#以及如何访问静态成员...我真的不知道如何解释它(对于一个问题有什么不好的不是吗?)我将给你一些示例代码:

Class test<T>{
     int method1(Obj Parameter1){
         //in here I want to do something which I would explain as
         T.TryParse(Parameter1);

         //my problem is that it does not work ... I get an error.
         //just to explain: if I declare test<int> (with type Integer)
         //I want my sample code to call int.TryParse(). If it were String
         //it should have been String.TryParse()
     }
}
Run Code Online (Sandbox Code Playgroud)

所以,谢谢你们的答案(顺便问一下:如果没有出现错误,我将如何解决这个问题).这对您来说可能是一个非常简单的问题!

谢谢,尼克拉斯


编辑:谢谢大家的回答!

虽然我认为try-catch短语是最优雅的,但我从vb的经验中知道它真的可能是一个无赖.我曾经用过一次,花了大约30分钟来运行一个程序,后来只花了2分钟来计算,因为我避免了尝试 - 捕获.

这就是我选择swich语句作为最佳答案的原因.它使代码更复杂,但另一方面,我认为它相对快速且相对容易阅读.(虽然我仍然认为应该有一种更优雅的方式......也许用我学习的下一种语言:P)


虽然如果你有其他建议,我还在等待(并愿意参加)

Gre*_*man 5

问题是TryParse没有在任何地方的接口或基类上定义,所以你不能假设传入你的类的类型将具有该功能.除非你能以某种方式反对T,否则你会遇到很多.

类型参数的约束


Tim*_*mbo 2

还有一种方法可以做到这一点,这次是在混合中进行一些反思:

static class Parser
{
    public static bool TryParse<TType>( string str, out TType x )
    {
        // Get the type on that TryParse shall be called
        Type objType = typeof( TType );

        // Enumerate the methods of TType
        foreach( MethodInfo mi in objType.GetMethods() )
        {
            if( mi.Name == "TryParse" )
            {
                // We found a TryParse method, check for the 2-parameter-signature
                ParameterInfo[] pi = mi.GetParameters();
                if( pi.Length == 2 ) // Find TryParse( String, TType )
                {
                    // Build a parameter list for the call
                    object[] paramList = new object[2] { str, default( TType ) };

                    // Invoke the static method
                    object ret = objType.InvokeMember( "TryParse", BindingFlags.InvokeMethod, null, null, paramList );

                    // Get the output value from the parameter list
                    x = (TType)paramList[1];
                    return (bool)ret;
                }
            }
        }

        // Maybe we should throw an exception here, because we were unable to find the TryParse
        // method; this is not just a unable-to-parse error.

        x = default( TType );
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

下一步将尝试实施

public static TRet CallStaticMethod<TRet>( object obj, string methodName, params object[] args );
Run Code Online (Sandbox Code Playgroud)

具有完整的参数类型匹配等。