当T是具有未知参数的泛型类时,如何访问类型为T的对象的属性? [英] How can I access property on object of type T, when T is a generic class with unknown parameter?

查看:43
本文介绍了当T是具有未知参数的泛型类时,如何访问类型为T的对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在处理参数类型T的对象的接口中有一个通用方法.一种实现方式需要访问类型T的属性,并且在该实现方式中,T的类型应为 ClassA< TC> ,其中TC是未知参数类型.我需要访问的属性位于 ClassA 本身上.

如何以一种安全的方式访问此Foo.Property?是否可以?我知道我可以使用动力学来做到这一点,但我想知道是否有其他方法.我已经尝试过IsAssignableFrom和其他检查,但似乎无法使其正常工作.

 接口IFace {void Request< T>(T foo);}类ClassA< T>{公共int财产;}class B:IFace {公共无效请求< T>(T foo){//我想断言Foo是ClassA,并访问该属性.} 

解决方案

做到这一点的最好方法是使 ClassA 实现一个定义所需属性的接口,然后约束T 到该界面.

可以访问约束的任何成员.您可以考虑一下"T",并希望该物业在那里,但您无法确定.专门存在一个接口,用于定义某些功能是通过任意类型实现的,因此几乎可以肯定是您所要查找的.

I have a generic method in an interface that works on objects of parameter type T. One implementation requires access to a property on type T, and in this implementation T is expected to be of type ClassA<TC> where TC is an unknown parameter type. The property I need to access is on ClassA itself.

How can I access this Foo.Property in a type safe way ? Is it possible? I know I can do it using dynamics, but I would like to know if there's a different way. I've tried IsAssignableFrom and other checks, but cant seem to get it working.

interface IFace {
    void Request<T>(T foo);
}

class ClassA<T> {
    public int Property;
}

class ClassB : IFace {
    public void Request<T>(T foo) {
    // I want to assert that Foo is of ClassA, and access the property. 

}

解决方案

The best way to do this is to make ClassA implement an interface which defines the property you want, and then constrain T to that interface.

Any members of the constraints can be accessed. You could reflect on 'T' and hope the property is there, but you'd have no way to be sure. An interface exists specifically to define that some functionality is implemented by an arbitrary type, and is therefore almost certainly what you're looking for.

这篇关于当T是具有未知参数的泛型类时,如何访问类型为T的对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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