Type of restriction for certain types

Is it possible to restrict the general method to certain types?

I want to write something like this:

public T GetValue<T>(string _attributeValue) where T : float, string
{
    return default(T); // do some other stuff in reality
}

I am just trying to avoid creating a gigantic expression switchinside a method or having to throw an exception if an invalid type is specified.

Edit: Ack. I knew it was stringnot a type of value. I started with two number types before. Unfortunately.

+3
source share
4 answers

, , . - , ( , ).

. , , .

, . , - . , .

float GetFloat(string attrName) { }
string GetString(string attrName) { }

" ", . , , . , , ( ). , - , (int vs. uint long).

float GetValue(string attrName, float defaultValue) { ... }
string GetValue(string attrName, string defaultValue) { ... }

, , , . , - , . ( , , ). , - , ... ( ) .

T GetValue<T>( string attrName )
{
   if( typeof(T) != typeof(string) ||
       typeof(T) != typeof(float) )
       throw new NotSupportedException();
   return default(T); 
}

// call it by specifying the type expected...
float f = GetValue<float>(attrName);
string s = GetValue<string>(attrName);

out . , , , .

void GetValue( string attrName, out float value )
void GetValue( string attrName, out string value )

// example of usage:
float f;
GetValue( attrName, out f );
string s;
GetValue( attrName, out s );
+5

. ( , T ) ( ) , .

+2

, .

, .

, , ( Nullable types):

public T GetValue<T>(string _attributeValue) where T : struct

, , ( /). , ...

Another option may also be to make your method confidential and provide special wrappers that are specific:

private T GetValue<T>(string _attributeValue) where T : struct
{
    return default(T);
}

public float GetFloatValue(string _attributeValue)
{
    return GetValue<float>(_attributeValue);
}

public int GetIntValue(string _attributeValue)
{
    return GetValue<int>(_attributeValue);
}

This will allow you to limit the public members of your class to the desired types, but still use the common code inside, so you don't need to repeat yourself.

+2
source

No, you cannot specify a range of types. If you want all the primitives you can do (and I know the line is not included)

 where T: struct
+1
source

Source: https://habr.com/ru/post/1758030/


All Articles