Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于在C中检索属性的类型化包装器#_C#_Attributes_Extension Methods - Fatal编程技术网

C# 用于在C中检索属性的类型化包装器#

C# 用于在C中检索属性的类型化包装器#,c#,attributes,extension-methods,C#,Attributes,Extension Methods,有一个自定义属性,允许声明用于序列化某个类的文件的扩展名: [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] public sealed class FileExtensionAttribute : Attribute { readonly string extension; readonly string description; public FileExten

有一个自定义属性,允许声明用于序列化某个类的文件的扩展名:

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class FileExtensionAttribute : Attribute {  
  readonly string extension;
  readonly string description;
  public FileExtensionAttribute(string extension, string description) {
    this.extension = extension;
    this.description = description;
  }
  public string Extension { get { return extension; } }
  public string Description { get { return description; } }
  public string GetFilterString() { return string.Format("{0}|*.{1}", description, extension); }
}
我用它给某个班级做了标记:

[FileExtension("users", "Contestants DB")]
public class UsersDB {
  //...
}
现在我使用反射来检索
GetFilterString()
result:

string filter = (Attribute.GetCustomAttribute(typeof(UsersDB), typeof(FileExtensionAttribute)) as FileExtensionAttribute).GetFilterString();
saveFileDialog.Filter = filter;
openFileDialog.Filter = filter;
我想写得更富于表现力,少长篇大论,比如:

UsersDB.Attributes.FileExtension.GetFilterString();
或者至少

AttributesOf(UsersDB).FileExtension.GetFilterString();

我希望这种语法适用于任何属性和类。

您可以像这样扩展对象

static class ObjectExtends
{

    public static T GetAttribute<T>(this object obj) where T : Attribute
    {
        return (T)Attribute.GetCustomAttribute(obj.GetType(), typeof(T));
    }
    public static T GetAttribute<T>(Type t) where T : Attribute
    {
        return (T)Attribute.GetCustomAttribute(t, typeof(T));
    }
}
静态类对象扩展
{
公共静态T GetAttribute(此对象对象对象),其中T:Attribute
{
return(T)Attribute.GetCustomAttribute(obj.GetType(),typeof(T));
}
公共静态T GetAttribute(类型T),其中T:Attribute
{
return(T)Attribute.GetCustomAttribute(T,typeof(T));
}
}
用法:

string s = "Hello World";
s.GetAttribute<SomeAttribute>();
string s=“Hello World”;
s、 GetAttribute();

ObjectExtends.GetAttribute(typeof(SomeClass));
ObjectExtends.GetAttribute<SomeAttribute>(typeof(SomeClass));