从对象到T的转换而无需转换操作符(T)实例

时间:2019-07-12 17:19:21

标签: c# reflection

我有两个通用类:A和B:

    // There we must know what T type parameter represents.
    public class A<TItem>
    {
        public void Method(IEnumerable<TItem> sequence)
        {
        }
    }

    // TObject can be everyone type. It is not constrained.
    public class B<TObject>
    {
        public void Method(TObject obj)
        {
            // Assume that we ensured that obj is IEnumerable<>.
        }
    }

假设我constructed instance的通用类型为A<IEnumerable<T>>。但是它的变量类型是object。是否有将object强制转换为A<IEnumerable<T>>的决定?

2 个答案:

答案 0 :(得分:0)

您的问题有点难以理解,因此进行澄清可能会提供更好的答案。
您可以通过简单的调用来创建A的实例:

var myA = new A<string>();

该类上的Method方法比这样的签名要好:

public void Method(IEnumerable<string> sequence)

答案 1 :(得分:0)

不确定这是否在计划中。

public class A<TItem>
    {
        public void Method(IEnumerable<TItem> sequence)
        {
        }
    }

    // TObject can be everyone type. It is not contrained.
    public class B<TObject>
    {
        public void Method(TObject obj)
        {
            // Assume that we ensured that obj is IEnumerable<>, but how to create instance of A?
            // May be there is another way to solve this problem...


            A<dynamic> f = new A<dynamic>();

            IEnumerable<string> list = new List<string>();

            f.Method(list);
        }
    }