繁体   English   中英

在c#上的静态方法中使用public属性

[英]Use a public attribute in a static method on c#

我创建了一个插件,我试图在一个类上使用它,问题是我试图在这个类中使用的方法是一个静态方法。

插件实现的结构是这样的:

插件使用struct

问题出在TestClass类的TestMethod方法中。 我不能使用TestPlugin属性,因为它不是静态属性。

我试图将它用作静态,但是当我更改它时, TestPlugin属性变为null 出于这个原因,我试图找到一种方法将它用作普通属性,但经过大量搜索后我找不到办法。

代码如下:

TestPlugin声明:

[ImportMany]
public IEnumerable<ITestPlugin> TestPlugin{ get; private set;}

使用TestPlugin属性:

private static void TestMethod(){
    ...
    // Here Visual Studio says that :
    //An object reference is required for the nonstatic field, method, or property 'ToastPlugin'
    foreach(plugin in TestPlugin){
       //Plugin's use
    }
    ...
}

编辑:

有没有办法使用的方式TestPluginTestMethod不宣TestPlugin为静态的,理由之前说的吗?

有没有办法在TestMethod中使用TestPlugin而不将TestPlugin声明为静态,原因如前所述?

快速回答是否定的。

基本上你有以下选择:

  1. 使TestPlugin静态的。
  2. 使TestMethod不是静态的。
  3. 使TestMethodTestClass对象的引用作为参数。
  4. 添加的静态集合IList<IEnumerable<ITestPlugin>> ,并在get / set的方法TestPlugin添加/新集合中删除的类。

你选择的那四个中的哪一个取决于你想要达到的目标。

暂无
暂无

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

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