将对象转换为泛型类型 [英] Cast object to a generic type

查看:376
本文介绍了将对象转换为泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个或多或少的泛型类:

我有一段时间没有睡,所以这可能比我想的要容易。 p>

  public class Reference< T>其中T:APIResource //<  -  APIResource是抽象的btw 
{
private T _value = null;
public T value
{
get {return _value; }
}
}

另外,在一个自定义序列化方法中,传入一个对象,它实际上是一个参考<(something)> 的实例。我只是想跳到每个 Reference<> 对象具有的value属性,所以我想去:

  string serialize(object o)
{
return base.serialize(((Reference<>)o).value);

当然,生活并不那么简单,因为编译器会说: b
$ b

使用泛型类型Reference< T>需要1个类型参数



我该怎么做我想做的事?

  interface IReference< out> 

T> T:ApiResource {
T Value {get; }
}

然后您可以投射 IReference< Anything> IReference< object> IReference< ApiResource>


I haven't slept in a while so this is probably easier than I think it is.

I have a generic class that's more or less this:

public class Reference<T> where T : APIResource //<- APIResource is abstract btw
{
    private T _value = null;
    public T value
    { 
        get { return _value; }
    }
}

Elsewhere, in a custom serialize method, someone is passing in an object that is actually an instance of Reference<(something)>. I simply want to skip to the "value" property that every Reference<> object has, so I want to go:

string serialize(object o)
{
    return base.serialize( ((Reference<>) o).value );
}

Of course, life isn't that simple because as the compiler puts it:

using the generic type "Reference<T>" requires 1 type arguments

How can I do what I want to do?

解决方案

You can create a covariant generic interface with the property:

interface IReference<out T> where T : ApiResource {
    T Value { get; }
}

You can then cast IReference<Anything> to IReference<object> or IReference<ApiResource>.

这篇关于将对象转换为泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆