简体   繁体   中英

Conversion to generic type

I have following property in C#:

public T Value
{
    get
    {
        ClassImNotAllowedToChange.GetValue<T>();
    }
    set
    {
        ClassImNotAllowedToChange.SetValue<T>(value);
    }
}

For some reasons I can't change the implementation of ClassImNotAllowedToChange , it may impose some limitations on my part of code. The problem here is that I want to save and read TimeSpan as seconds amount, converted to int . And while I can easily write whatever I want in setter , getter restricts me to use only generic type T , which makes impossible something like this:

get
{
    if (typeof(T) == typeof(TimeSpan))
        return (T)TimeSpan.FromSeconds(ClassImNotAllowedToChange.GetValue<int>());

    return PlcItem.GetValue<T>();
}

There is no implicit conversion from int to TimeSpan , so the first code listing causes an InvalidCastException in runtime. Is there any workaround to convert int to TimeSpan within getter or it's better to find another way of implementation?

As workaround you can cast TimeSpan.FromSeconds to object and then to T (with corresponding performance hit):

get
{
    if (typeof(T) == typeof(TimeSpan))
        return (T)(object)TimeSpan.FromSeconds(ClassImNotAllowedToChange.GetValue<int>());

    return PlcItem.GetValue<T>();
}

But I would recommend to rework your code somehow so you will not need to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM