带有 DateTime 参数的 .NET Standard 程序集属性
.NET Standard assembly attribute with DateTime parameter
背景
我正在尝试实现一个自定义属性,该属性可应用于 .NET 程序集以指示到期日期(开发人员不支持使用已分发的预发布版本的日期用于检测)。它必须用 .NET Standard (2.0) 编写。
我知道我不能将 DateTime
作为参数传入,所以我传入一个符合 ISO8601 (YYYY-MM-DD) and then using DateTime.Parse()
的字符串以转换为 DateTime
。
目前我得到的属性如下:
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
public sealed class UnstableReleaseExpiryAttribute : Attribute
{
public UnstableReleaseExpiryAttribute(string expiryDate)
{
ExpiryDate = expiryDate;
}
public DateTime Expiry
{
get
{
if (ExpiryDate != null && DateTime.TryParse(ExpiryDate, out DateTime expiry))
return expiry;
return DateTime.MaxValue;
}
}
public string ExpiryDate { get; }
}
这就是我打算如何使用它:
[assembly: UnstableReleaseExpiry("2018-05-24")]
问题
有没有一种方法可以使用正则表达式来验证字符串输入,并在日期实际上不可解析时阻止它被编译?我环顾四周,认为从 ValidationAttribute
继承是实现它的方法,但它似乎在 .NET Standard 2.0 中不可用。还有其他方法吗?
没有。目前没有。 ValidationAttribute
只是一个"annotation",关于field/property应该是什么格式。其他 C# 代码必须激活它。
- 您可以创建代码分析规则来检查这一点。
- 类似问题:Is it possible to query custom Attributes in C# during compile time ( not run-time ), Postsharp compile-time validation on interface methods。您可以使用
Fody
而不是 PostSharp
可能
- 我使用的简单解决方案(因为处理post-编译步骤很痛苦,代码分析器可以被禁用):如果你有一个单元测试项目,做一个使用反射找到所有的测试属性的用法并检查它。
背景
我正在尝试实现一个自定义属性,该属性可应用于 .NET 程序集以指示到期日期(开发人员不支持使用已分发的预发布版本的日期用于检测)。它必须用 .NET Standard (2.0) 编写。
我知道我不能将 DateTime
作为参数传入,所以我传入一个符合 ISO8601 (YYYY-MM-DD) and then using DateTime.Parse()
的字符串以转换为 DateTime
。
目前我得到的属性如下:
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
public sealed class UnstableReleaseExpiryAttribute : Attribute
{
public UnstableReleaseExpiryAttribute(string expiryDate)
{
ExpiryDate = expiryDate;
}
public DateTime Expiry
{
get
{
if (ExpiryDate != null && DateTime.TryParse(ExpiryDate, out DateTime expiry))
return expiry;
return DateTime.MaxValue;
}
}
public string ExpiryDate { get; }
}
这就是我打算如何使用它:
[assembly: UnstableReleaseExpiry("2018-05-24")]
问题
有没有一种方法可以使用正则表达式来验证字符串输入,并在日期实际上不可解析时阻止它被编译?我环顾四周,认为从 ValidationAttribute
继承是实现它的方法,但它似乎在 .NET Standard 2.0 中不可用。还有其他方法吗?
没有。目前没有。 ValidationAttribute
只是一个"annotation",关于field/property应该是什么格式。其他 C# 代码必须激活它。
- 您可以创建代码分析规则来检查这一点。
- 类似问题:Is it possible to query custom Attributes in C# during compile time ( not run-time ), Postsharp compile-time validation on interface methods。您可以使用
Fody
而不是PostSharp
可能 - 我使用的简单解决方案(因为处理post-编译步骤很痛苦,代码分析器可以被禁用):如果你有一个单元测试项目,做一个使用反射找到所有的测试属性的用法并检查它。