开发者

Variable of unspecified type in C#?

开发者 https://www.devze.com 2023-03-15 09:14 出处:网络
Is it possible for me to declare a variable, without a type, then specify the type based on some conditions? For example, I want to create a SHA Hash object based what size the user would like to use:

Is it possible for me to declare a variable, without a type, then specify the type based on some conditions? For example, I want to create a SHA Hash object based what size the user would like to use:

        //get the Sha hasher
        var shaHash;

        switch (this.HASH_ALGORITHM)
        {
            case HashAlgorithm.SHA256:  //HashAlgorithm is an enum.
                shaHash = SHA256.Create();
                break;
            case HashAlgorithm.SHA384:
                shaHash = SHA384.Create();
                break;
            case HashAlgorithm.SHA512:
                shaHash = SHA512.Create();
          开发者_C百科      break;
        }

        //... do hashing

Is this possible?


No, that won't work. But, given that all three of those types inherit from System.Security.Cryptography.HashAlgorithm, you could declare the variable of that type:

HashAlgorithm shaHash;

switch(this.HASH_ALGORITHM)
{
    // snip
}

Edit

Just to add, the reason that var shaHash; will not work is because that var is just a shorthand way of saying "I'm not sure of the best type to use here, so please infer it for me". The compiler requires that you specify an initial value so that it can determine the best type to use.


Not without resorting to dynamic; you need to use inheritance or interfaces for this. So the type could be e.g. object, or if the different SHA classes have another common superclass or if they implement some interface, you could use that superclass or interface. Otherwise, you could create adapter classes with a common superclass and wrap the SHA objects in the adapters.


Use base type:

HashAlgorithm shaHash = null;


If you have a parent class in which you declare a type, and 3 other classes which inherit after the parent class (children), then you can create a method which would be declared as returning the parent type, but inside you would return each of the child types. This will work and compile as the parent type will be automatically casted on to a child type. It will not work the other way round however (you cannot cast a type from a child to parent).


It is not posible. In order to use var you need the compiler to know what will the type of your variable be and that is only posible when you assign a value. Also you cannot say var varname = null; because null does not define a type.


In c# 4 you can declare a dynamic type.

0

精彩评论

暂无评论...
验证码 换一张
取 消