简体   繁体   中英

C# custom attributes - how to validate constructor's arguments?

I have a custom attribute that defines some application version for a method:

[AttributeUsage(AttributeTargets.Method)]
class ProjectConverterAttribute : Attribute
{
    public Version BaseVersion { get; private set; }
    public Version TargetVersion { get; private set; }

    public ProjectConverterAttribute( string baseVersion, string targetVersion )
    {
        BaseVersion = new Version(baseVersion);
        TargetVersion = new Version(targetVersion);
    }
}

An instance of Version class can be initialized with a string representation: "major.minor[.build[.revision]]"

Now I can specify any string as a parameter and get the runtime exception caused by errors of parsing only when this code is executed by using Reflection methods:

[ProjectConverter( "1.0.1.215","1.0.1.R220")]
bool Convert( Project project )
{
}

Is there a way to validate this value with highlighting in the code editor? Like it works for AssemblyVersionAttribute with the same version-formatted string as a parameter. It can be found in the file Properties\\AssemblyInfo.cs .

[assembly: AssemblyVersion("1.0.904.2")]

If I try to exceed the value, this sting will be highlighted as an error at design time.

这可以通过编写自己的自定义Visual Studio分类器扩展( https://msdn.microsoft.com/zh-cn/library/dd885492.aspx )来完成。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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