"使用未分配的局部变量"错误与接口

Kas*_*hif 1 c# null interface

我遇到了一些语法问题.我对界面并不熟悉,请原谅我的无知.

VS2010给我一个错误... application.Name = System.AppDomain.CurrentDomain.FriendlyName;

public static void AddApplication(string applicationName = null, string processImageFileName = null)
{
    INetFwAuthorizedApplications applications;
    INetFwAuthorizedApplication application;

    if(applicationName == null)
    {
        application.Name = System.AppDomain.CurrentDomain.FriendlyName;/*set the name of the application */
    }
    else
    {
        application.Name = applicationName;/*set the name of the application */
    }

    if (processImageFileName == null)
    {
        application.ProcessImageFileName = System.Reflection.Assembly.GetExecutingAssembly().Location; /* set this property to the location of the executable file of the application*/
    }
    else
    {
        application.ProcessImageFileName = processImageFileName; /* set this property to the location of the executable file of the application*/
    }

    application.Enabled =  true; //enable it

    /*now add this application to AuthorizedApplications collection */
    Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); 
    INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType); 
    applications = (INetFwAuthorizedApplications)mgr.LocalPolicy.CurrentProfile.AuthorizedApplications;
    applications.Add(application);
}
Run Code Online (Sandbox Code Playgroud)

我可以通过设置application来消除该错误,null但这会导致运行时空引用错误.

编辑:

这是我正在调整代码的地方.我希望它能提供更多背景信息 http://blogs.msdn.com/b/securitytools/archive/2009/08/21/automating-windows-firewall-settings-with-c.aspx

Eri*_* J. 8

你永远不会初始化

application
Run Code Online (Sandbox Code Playgroud)

在这里使用之前:

application.Name = System.AppDomain.CurrentDomain.FriendlyName;
Run Code Online (Sandbox Code Playgroud)

变量应用程序定义为:

INetFwAuthorizedApplication application
Run Code Online (Sandbox Code Playgroud)

您需要分配实现该接口的类的实例INetFwAuthorizedApplication.

在某个地方,项目中必须有一个(或可能更多)类看起来像这样:

public class SomeClass : INetFwAuthorizedApplication
{
    // ...
}

public class AnotherClass : INetFwAuthorizedApplication
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

你需要确定你应该使用哪个类(SomeClass,AnotherClass)然后分配一个合适的对象,例如:

INetFwAuthorizedApplication application = new SomeClass();
Run Code Online (Sandbox Code Playgroud)

  • @Kashif:创建一个接口实例是没有意义的.它到底会做什么?您可以将变量声明为接口类型,但是您必须创建或获取要分配给它的具体实现的实例,即`SomeInterface x = new SomeInterfaceImplementation();`或SomeInterface x = GetSomeObject();` (2认同)
  • @Kashif看来这些接口处理windows防火墙.一些谷歌搜索导致这个博客:http://blog.csharphelper.com/2010/10/09/access-firewall-information-and-check-firewall-status-using-the-dynamic-keyword-in-c.aspx和这个msdn页面:http://msdn.microsoft.com/library/system.activator.aspx您需要使用Activator类来获取实现INetFwAuthorizedApplication的实例 - Activator.CreateInstance()似乎是一个工厂方法,生成您需要的实例. (2认同)