Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何加载从窗体和接口扩展的类?_C#_Interface_Casting_Extend - Fatal编程技术网

C# 如何加载从窗体和接口扩展的类?

C# 如何加载从窗体和接口扩展的类?,c#,interface,casting,extend,C#,Interface,Casting,Extend,我有几个扩展了基于表单和自定义接口的表单类 Interface InterfaceForms{ void InterfaceFunc1(); } public partial class child1 : Form, InterfaceForms { public child1(){} public InterfaceFunc1(){} } public partial class child2 : Form, InterfaceFor

我有几个扩展了基于表单和自定义接口的表单类

Interface InterfaceForms{
      void InterfaceFunc1();
}



public partial class child1 : Form, InterfaceForms
    {
      public child1(){}
      public InterfaceFunc1(){}
    }

public partial class child2 : Form, InterfaceForms
    {
      public child2(){}
      public InterfaceFunc1(){}
    }
我将所有表单类对象添加到列表中,如下所示:

 List<Form> lsf = new List<Form>();
 var fr = from Form item in lsf
                         where item.Name == "child1"
                         select item;
Form frm = (Form)fr;
现在,我的问题是无法访问InterfaceFunc1()


你介意告诉我如何实施这一点吗?请注意,frm类型每次可能不同(child1、child2等),但它们都是从表单和InterfaceForm扩展而来的。

您需要将其转换为
InterfaceForms

var fr = from Form item in lsf
                         where item.Name == "child1"
                         select item;
Form frm = (Form)fr;
var iFaceFrm = frm as InterfaceForms;

if (iFaceFrm != null)
{
    //use the iFaceFrm or frm here
}
编辑

LINQ语句的问题是声明类型,LINQ语句的类型是推断的,因此您不会将其放入select:

var fr = from item in lsf
         where item.Name == "child1"
         select item;
或者,如果您想按程序进行:

var fr = lsf.Where(f => f.Name == "child1").FirstOrDefault();

您需要将其转换为
接口表单

var fr = from Form item in lsf
                         where item.Name == "child1"
                         select item;
Form frm = (Form)fr;
var iFaceFrm = frm as InterfaceForms;

if (iFaceFrm != null)
{
    //use the iFaceFrm or frm here
}
编辑

LINQ语句的问题是声明类型,LINQ语句的类型是推断的,因此您不会将其放入select:

var fr = from item in lsf
         where item.Name == "child1"
         select item;
或者,如果您想按程序进行:

var fr = lsf.Where(f => f.Name == "child1").FirstOrDefault();

是的,因为
表单
没有实现
接口表单
,所以实际上你需要一个
列表
,以便调用该列表项上的函数。是的,因为
表单
没有实现
接口表单
,因此,实际上您需要有一个
列表
,以便调用该列表项上的函数。Tq建议的代码是正确的。我不知道为什么第一个linq部件不能正常工作。我使用这个条件来获取表单对象,它工作得很好。你能检查一下我写的linq并找出问题所在吗?Tq建议的代码是正确的。我不知道为什么第一个linq部件不能正常工作。我使用这个条件来获取表单对象,它工作得很好。你能检查一下我写的linq,找出问题所在吗?