简体   繁体   English

在C#中将通用对象转换回原始对象

[英]Casting generic objects back to the original object in C#

I having trouble casting from a generic back to the original object in C# 我无法从通用转换回C#中的原始对象

private static bool OpenForm<T>( )
{
    List<T> list = FormManager.GetListOfOpenForms<T>();
    if ( list.Count == 0 )
    {
        // not opened
        return false;
    }
    else
    {
        // opened
        foreach ( T f in list )
        {
            T ff = ( T ) Convert.ChangeType( f, typeof( T ) );

if I type ff. 如果我键入ff。 and intellisense pops up with the just a few methods and properties. 并且intellisense弹出了一些方法和属性。

how can I have a variable here where it exposes all properties and methods of ff 我怎么能在这里有一个变量,它暴露了ff的所有属性和方法

        }
        return true;
    }
}

Since it is a generic method, T could literally be any type, down to a simple object . 由于它是一种通用方法,因此T可以是任何类型,直到一个简单的object The compiler - and likewise the intellisense engine - has no idea what T is until runtime. 编译器 - 以及智能感知引擎 - 直到运行时才知道T是什么。 Note that this is of course the behavior you want, and it is the reason you use generics in the first place. 请注意,这当然是您想要的行为,这也是您首先使用泛型的原因。 In this case, using static typing, there is no way to access the members of T outside of reflection. 在这种情况下,使用静态类型,无法访问反射之外的T成员。

Now what I believe you are looking for is a constraint, that is to say that all T s will always be of a certain base type. 现在我认为你正在寻找的是一个约束,也就是说所有的T 将是一个特定的基类型。 For example, if all T s will be Form s, you can put a constraint on the method and then access the members of Form : 例如,如果所有T都是Form s,则可以对方法设置约束,然后访问Form的成员:

private static bool OpenForm<T>() where T : Form
{
    List<T> list = FormManager.GetListOfOpenForms<T>();
    if ( list.Count == 0 )
    {
        // not opened
        return false;
    }
    else
    {
        // opened
        foreach ( T f in list )
        {
            f.Text = "You found me!";
        }
    }
}

Note I have omitted your conversion from T f to T ff since it would do nothing. 注意我已经省略了从T fT ff转换,因为它什么都不做。

if T has some sort of common base class(common type), use generic constraints so that the compiler will know that at minimum T will support the methods on the common class. 如果T具有某种公共基类(公共类型),则使用泛型约束,以便编译器知道至少T将支持公共类上的方法。 http://msdn.microsoft.com/en-us/library/d5x73970.aspx http://msdn.microsoft.com/en-us/library/d5x73970.aspx

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

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