这会导致编译时异常:
public sealed class ValidatesAttribute<T> : Attribute
{
}
[Validates<string>]
public static class StringValidation
{
}
Run Code Online (Sandbox Code Playgroud)
我意识到C#不支持通用属性.然而,经过大量的谷歌搜索,我似乎无法找到原因.
有谁知道为什么泛型类型无法衍生出来Attribute?任何理论?
虽然C#规范确实包含预处理器和基本指令(#define,#if等),但该语言没有与C/C++等语言相同的灵活预处理器.我认为缺乏这种灵活的预处理器是由Anders Hejlsberg做出的设计决定(尽管不幸的是,我现在找不到这个参考).根据经验,这肯定是一个很好的决定,因为当我做很多C/C++时,会创建一些非常糟糕的不可维护的宏.
也就是说,有很多场景我可以找到一个稍微灵活一点的预处理器.一些简单的预处理器指令可以改进以下代码:
public string MyProperty
{
get { return _myProperty; }
set
{
if (value != _myProperty)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
// This line above could be improved by replacing the literal string with
// a pre-processor directive like "#Property", which could be translated
// to the string value "MyProperty" This new notify call would be as follows:
// NotifyPropertyChanged(#Property);
}
}
}
Run Code Online (Sandbox Code Playgroud)
编写预处理器来处理这样极其简单的情况会不是一个好主意?Steve McConnell在Code Complete中写道(p208):
编写自己的预处理器 如果一种语言不包含预处理器,那么编写一个很容易...
我被撕裂了.将这样一个灵活的预处理器从C#中取出是一个设计决定.但是,我非常尊重的作者提到它在某些情况下可能没问题.
我应该构建一个C#预处理器吗?有没有可以做我想做的简单事情?
当我尝试使用.NET 2.0或3.0运行时添加扩展方法时,我收到错误:
无法定义新的扩展方法,因为无法找到编译器所需的类型"System.Runtime.CompilerServices.ExtensionAttribute".您是否缺少对System.Core.dll的引用?
但是当我尝试将它添加到项目中时,我无法在可用引用列表中找到System.Core.我需要做什么才能在我的项目中使用扩展方法和LINQ on?