2

我遇到了一些语法问题。我对接口不是很熟悉,所以请原谅我的无知。

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);
}

我可以通过设置application为使该错误消失,null但这会导致运行时空引用错误。

编辑:

这是我改编代码的地方。我希望它提供更多上下文 http://blogs.msdn.com/b/securitytools/archive/2009/08/21/automating-windows-firewall-settings-with-c.aspx

4

2 回答 2

9

你从不初始化

application

在这里使用它之前:

application.Name = System.AppDomain.CurrentDomain.FriendlyName;

变量应用程序定义为:

INetFwAuthorizedApplication application

您需要分配一个实现接口的类的实例INetFwAuthorizedApplication

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

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

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

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

INetFwAuthorizedApplication application = new SomeClass();
于 2012-07-09T20:05:14.820 回答
1

接口用于描述一个对象的作用,而不是它具体是什么。用“现实世界”的术语来说,一个界面可能是这样的:

ISmallerThanABreadbox用一种FitIntoBreadbox()方法。我不能要求你给我“比面包盒还小的东西​​”……因为这没有任何意义。我只能要求你给我一些“比面包盒还小”的东西。你必须想出你自己的对象,这个对象对它有接口是有意义的。苹果比面包盒小,所以如果你的面包盒只能装比它小的东西,那么苹果就是一个很好的ISmallerThanABreadbox接口候选者。

另一个例子是IGraspable方法Hold()FitsInPocket布尔属性。你可以要求得到一些可以抓握的东西,可能装在你的口袋里,也可能放不下,但你不能要求“可抓握的”。

希望有帮助...

于 2012-07-09T20:17:14.560 回答