C# Getting Type out of a string variable and using it in generic method

前端 未结 3 1488
灰色年华
灰色年华 2021-01-29 05:59

I want to be able to get the actual Type of a string value I receive by some means (i.e from database) so I can use that Type in generic method like DoSomething

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-29 06:33

    If Register does something like this

    void Register(int id)
    {
        _dictionary.Add(typeof(T), ...);
    }
    

    Create a non generic overload

    void Register(Type t, int id)
    {
        _dictionary.Add(t, ...);
    }
    

    This new overload is not type safe, but creating a type out of a string isn't anyway.

    The purpose of generics is to gain variability (not to be confused with dynamic behavior!) while keeping type safety. But when types are determined at runtime, type safety is not given and generics are more of a hindrance than useful.

    Note that type safety is ensured by the compiler, which does of course not work at runtime.

提交回复
热议问题