使用属性防止在设计时执行方法

时间:2015-11-07 05:03:12

标签: c# methods attributes

如果方法处于设计时或者方法只能在运行时执行,是否有办法阻止方法执行。

我在创建自定义控件时遇到了这个问题,因为构造函数中只有一个方法调用只能在运行时运行。

现在在设计表单时使用该控件,然后表单将生成错误。 现在我在用户控件的构造函数中尝试了这个

    public ctrl_information()
    {
        InitializeComponent();
        if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)) return;
        SomeMethod();
        //Other code
    }

我现在想要达到的目标是这样的。

[ExecuteOnlyAtRuntime]
public void SomeMethod()
{
     //Code here
}

然后这样称呼它。

public ctrl_information()
    {
        InitializeComponent();
        //if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)) return; -- removing this line
        SomeMethod();
    }

有可能吗?

请对此有所了解。

谢谢

1 个答案:

答案 0 :(得分:0)

假设someMethod在控件中,您可以使用Component.DesignMode。

所以一个简单的方法可能是

    public void SomeMethod()
    {
        if (this.DesignMode == false)
        {
            //Code here
        }           
    }

如果某些功能不在控件中,您可以实现类似的功能 -

public void SomeFunciton()
    {
        if(VisualStudioUtility.IsRunningInVisualStudio == false)
        {

        }
    }



 static class VisualStudioUtility
{
    private const string IDE_EXE = "devenv.exe";

    public static bool IsRunningInVisualStudio
    {
        get
        {
            return Environment.CommandLine.Contains(IDE_EXE);
        }
    }
}