General type function (property)

I am trying to return a value of type T.

public T this[int index]
{
     get
     {
           if (typeof(T) == typeof(int))
              return (T) dynEx[index].Int;
           else if (typeof(T) == typeof(string))
              return (T) dynEx[index].Str;
     }
}

dynEx is a complex object that returns an object based on some custom expression.

Obviously, the code does not work because it has an error: "it is impossible to convert the type" int "to T" and "cannot convert the type" string "to T".

How can I achieve this without affecting performance?

This property is called over a thousand times per frame (this is a game).

+4
source share
1 answer

int, object -, . , , , # generics - , , . , :

public T this[int index]
{
    get
    {
        if (typeof(T) == typeof(int))
        {
            return (T) (object) dynEx[index].Int;
        }
        else if (typeof(T) == typeof(string))
        {
            return (T) (object) dynEx[index].Str;
        }
        // TODO: Whatever you want to happen if T isn't int/string
    }
}
+3

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


All Articles