C# 如何从类型列表中获取泛型类型
我想将接口列表作为参数传递给方法。C# 如何从类型列表中获取泛型类型,c#,list,generics,C#,List,Generics,我想将接口列表作为参数传递给方法。 然后我想遍历这个列表来调用一个泛型方法。 我该怎么做 //the interfaces public interface IView{} public interface IView1 : IView {} public interface IView2 : IView {} //the forms public partial class MyView1 : Form, IView1 {} public partial class MyView2 : For
然后我想遍历这个列表来调用一个泛型方法。
我该怎么做
//the interfaces
public interface IView{}
public interface IView1 : IView {}
public interface IView2 : IView {}
//the forms
public partial class MyView1 : Form, IView1 {}
public partial class MyView2 : Form, IView2 {}
//this works
var myOpenForm = GetForm<IView1>();
//this doesn't work
var myList = new List<T> { IView1, IView2 }; <-- ERROR: IView1 is a type, which is not valid in the given context
var myOpenForm = GetFirstForm(myList);
//find the first form open of the specified types
public static T GetFirstForm(List<T> viewTypes)
{
foreach (var myType in viewTypes)
{
var form = GetForm<myType>(); <-- ERROR: myType is a variable but is used like a type
if(form != null)
{
return form;
}
}
}
//find form of type T if it is open in the application
public static T GetForm<T>()
{
foreach (var form in Application.OpenForms)
{
if (form is T)
{
return (T)form;
}
}
return default(T);
}
//接口
公共接口IView{}
公共接口IView1:IView{}
公共接口IView2:IView{}
//表格
公共部分类MyView1:Form,IView1{}
公共部分类MyView2:Form,IView2{}
//这很有效
var myOpenForm=GetForm();
//这不管用
var myList=新列表{IView1,IView2} 不能存储类型。您可以存储对象。您可以使用typeof
或GetType()
获取包含类型元数据的对象。此外,类型参数在编译时是固定的,所以不能在运行时从变量填充它们
所以不是这个
var myList = new List<T> { IView1, IView2 };
Resharper告诉我使用type.IsInstanceOfType(form)
,而不是type.IsAssignableFrom(form.GetType())
,但它可以编译。另外,获取表单的目的是在IView上调用一个方法,因此我必须强制转换结果,我想这是不可避免的
var myList new List<Type> { typeof(IView1), typeof(IView2) };
public static Form GetFirstForm(List<Type> viewTypes)
{
foreach (var myType in viewTypes)
{
var form = GetForm(myType);
if(form != null)
{
return form;
}
}
}
public static Form GetForm(Type type)
{
foreach (var form in Application.OpenForms)
{
if (type.IsAssignableFrom(form.GetType()))
{
return form;
}
}
return null;
}