简体   繁体   English

转换为泛型

[英]Conversion to generic type

I have following property in C#:我在 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.由于某些原因,我无法更改ClassImNotAllowedToChange的实现,它可能会对我的部分代码施加一些限制。 The problem here is that I want to save and read TimeSpan as seconds amount, converted to int .这里的问题是我想将TimeSpan保存并读取为秒数,转换为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:虽然我可以轻松地在setter中编写任何我想要的东西,但getter限制我只能使用泛型类型T ,这使得这样的事情变得不可能:

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.没有从intTimeSpan的隐式转换,因此第一个代码清单会在运行时导致InvalidCastException Is there any workaround to convert int to TimeSpan within getter or it's better to find another way of implementation?是否有任何解决方法可以在getter中将int转换为TimeSpan或者最好找到另一种实现方式?

As workaround you can cast TimeSpan.FromSeconds to object and then to T (with corresponding performance hit):作为解决方法,您可以将TimeSpan.FromSeconds转换为object ,然后转换为T (具有相应的性能影响):

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.但我会建议以某种方式重新编写您的代码,这样您就不需要这样做了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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