Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.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# - Fatal编程技术网

是否可以将静态对象添加到C#中的列表中?

是否可以将静态对象添加到C#中的列表中?,c#,C#,我有一堆静态类,我想通过将它们全部添加到列表中来轻松访问它们 有没有办法将这些静态类添加到列表中?我得到一个“这个类型像变量一样使用”错误 公共静态类PCM1\u设置:IGUI\u到\u BFC { //PCM1_格式 公共静态无效设置\u toBFC() { //使用复选框更新BFC //根据复选框确定要写入字段的值 RegmapInputReader.BitField BF; GB.BFC.name_to_BitField_Dict.TryGetValue(“PCM1_格式”,out BF)

我有一堆静态类,我想通过将它们全部添加到列表中来轻松访问它们

有没有办法将这些静态类添加到列表中?我得到一个“这个类型像变量一样使用”错误

公共静态类PCM1\u设置:IGUI\u到\u BFC
{
//PCM1_格式
公共静态无效设置\u toBFC()
{
//使用复选框更新BFC
//根据复选框确定要写入字段的值
RegmapInputReader.BitField BF;
GB.BFC.name_to_BitField_Dict.TryGetValue(“PCM1_格式”,out BF);
}
公共静态无效设置\u fromfc()
{
//设置来自BFC的复选框
}
}
公共静态类PC2
{
List abe=新列表();
PC2()
{
abe.Add(PCM1_Setup);//此处出错----------------------
}
}

不能将类型作为方法参数传递。使
PCM1\u设置
类为非静态的及其所有方法实例方法(不带
static
修饰符),并将该类的新实例作为
abe.Add的参数传递将解决此问题

或者,您可以将
abe
设置为
List
类型,并使用
typeof
操作符添加对
PCM1\u设置类型的引用

List<Type> abe = new List<Type>();

PC2()
{
    abe.Add(typeof(PCM1_Setup));
}

记住上面的例子,它不是最好的选择,最好使用第一个。

您使用的是静态类。因此,您从来没有可以添加到列表中的实例。如果您想拥有一个实例并访问它,而不需要每次都创建一个新实例,那么您可以实现某种形式的单例。然后,您可以将单例实例添加到列表中

public class PCM1_Setup : IGUI_to_BFC
{
    private static PCM1_Setup instance;

    public static PCM1_Setup Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new PCM1_Setup();
            }

            return instance;
        }
    }

    private PCM1_Setup()
    {

    }

    ...
}
PCM1_设置类不再是静态的。该方法还应作为实例方法实现。 然后将示例中的一个单例实例添加到列表中:

public static class PC2
{
    static List<IGUI_to_BFC> abe = new List<IGUI_to_BFC>();
    static PC2()
    {
        abe.Add(PCM1_Setup.Instance);
    }
}

不清楚你的最终目标是什么。。。看起来您试图手动重新创建虚拟函数(或接口),但一些澄清可能有助于回答问题。您无法创建静态类的实例,因此需要澄清目标。静态成员也无法实现接口。您应该考虑不使用静态类。我试图创建这些控件的集合,这些控件都具有相同的接口(成员函数),因此我可以将所有控件添加到列表中,并为列表中的每个项目做*.SETUP()。我想我必须用一个抽象类来实现它?哦,我一直认为静态是一个单例,只是在运行时创建的一个对象。:)今天模特破了哈哈。谢谢
public class PCM1_Setup : IGUI_to_BFC
{
    private static PCM1_Setup instance;

    public static PCM1_Setup Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new PCM1_Setup();
            }

            return instance;
        }
    }

    private PCM1_Setup()
    {

    }

    ...
}
public static class PC2
{
    static List<IGUI_to_BFC> abe = new List<IGUI_to_BFC>();
    static PC2()
    {
        abe.Add(PCM1_Setup.Instance);
    }
}
((PCM1_Setup)abe[0]).Setup_fromBFC();