Declare a variable using a Type variable

后端 未结 6 1455
借酒劲吻你
借酒劲吻你 2020-12-06 09:28

I have this code:

Type leftType = workItem[LeftFieldName].GetType();

I then want to declare a variable of that type:

leftTy         


        
相关标签:
6条回答
  • 2020-12-06 09:56

    GetType is evaluated at run-time, and non-dynamic declaration is at compile-time (it does get more specific than that, yes), so no. Even var will require you to assign a value to it that is of unambiguous type.

    0 讨论(0)
  • 2020-12-06 09:59

    You can do something like these and cast them to a known interface.

    var someVar = Convert.ChangeType(someOriginalValue, workItem[LeftFieldName].GetType());
    var someVar = Activator.CreateInstance(workItem[LeftFieldName].GetType());
    

    If you replace var with dynamic (and you are using .Net 4), you can call the methods you expect on the someVar object. If they don't exist, you'll just get a MissingMethodException.

    0 讨论(0)
  • 2020-12-06 09:59

    No, that is not possible. The type of a variable has to be known at compile time.

    You can declare a variable of type object, it will be capable of storing any data type.

    0 讨论(0)
  • 2020-12-06 10:05

    You cannot do that.

    You could use the dynamic type for .Net 4, but for earlier .Net versions, the only type that will fit is object, which you will need to manually cast later by again testing .GetType() on what you assigned to the object-typed variable.

    Reading: SO link: whats-the-difference-between-dynamicc-4-and-var

    0 讨论(0)
  • 2020-12-06 10:06

    object x = Activator.CreateInstance(Type) will let you create the object. Whether you can do much with it beyond that point, I'm not sure.

    0 讨论(0)
  • 2020-12-06 10:10

    This is not possible.

    Variable types are a compile-time concept; it would make no sense to declare a variable of a type which is not known until runtime.
    You wouldn't be able to do anything with the variable, since you wouldn't know what type it is.

    You're probably looking for the dynamic keyword.

    0 讨论(0)
提交回复
热议问题