Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.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#_.net_Generics_Reflection_Attributes - Fatal编程技术网

C# 从类型的成员获取属性的泛型方法

C# 从类型的成员获取属性的泛型方法,c#,.net,generics,reflection,attributes,C#,.net,Generics,Reflection,Attributes,我创建了一个方便的方法,使用泛型检索应用于类型的属性: /// <summary> /// Return an attribute from the provided type if it exists on that type. /// </summary> /// <typeparam name="T">The type whose attribute <typeparamref name="TAttType"/> /// will be r

我创建了一个方便的方法,使用泛型检索应用于类型的属性:

/// <summary>
/// Return an attribute from the provided type if it exists on that type.
/// </summary>
/// <typeparam name="T">The type whose attribute <typeparamref name="TAttType"/> 
/// will be returned if it exists on that type.</typeparam>
/// <typeparam name="TAttType">The type of attribute that will be retrieved
/// on <typeparamref name="T"/> if it exists.</typeparam>
/// <returns>Return the attribute with type <typeparamref name="TAttType"/>, 
/// if it exists, from target type <typeparamref name="T"/> or else
/// return null.</returns>
public static TAttType GetAttribute<T, TAttType>() where TAttType:Attribute 
    => (TAttType) typeof(T).GetCustomAttribute(typeof(TAttType), false);
我可以这样做:

[Vehicle("Yellow", 6)]
public class Bus { }
然后这个:

var att = ReflectionTools.GetAttribute<Bus, VehicleAttribute>();

我希望能够使用类似的方法。是否有一种方法可以使用泛型来方便从任何
System.Reflection.MemberInfo
(而不仅仅是
System.Type
)检索属性?

您可以使用
MemberExpression
指定要从中获取属性的成员。以下是一个例子:

using System;
using System.Linq.Expressions;
using System.Reflection;

public class VehicleAttribute : Attribute
{
    public string Color { get; }
    public int NumWheels { get; }

    public VehicleAttribute(string color, int numWheels)
    {
        Color = color;
        NumWheels = numWheels;
    }
}

[Vehicle("Yellow", 6)]
public class Bus
{ 

    [Vehicle("Blue", 5)]
    public string Name { get; set; }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(Test<Bus, VehicleAttribute>((x) => x.Name).Color);
    }

    static U Test<T, U>(Expression<Func<T, object>> expr) where U : Attribute
    {
        if(!(expr.Body is MemberExpression memberExpr))
        {
            throw new NotSupportedException("expr");
        }
        return (U)memberExpr.Member.GetCustomAttribute(typeof(U), false);
    }
}
使用系统;
使用System.Linq.Expressions;
运用系统反思;
公共类车辆属性:属性
{
公共字符串颜色{get;}
public int NumWheels{get;}
公共车辆属性(字符串颜色,整数跟数)
{
颜色=颜色;
NumWheels=NumWheels;
}
}
[车辆(黄色),6)]
公车
{ 
[车辆(蓝色),5)]
公共字符串名称{get;set;}
}
公共课程
{
公共静态void Main()
{
Console.WriteLine(测试((x)=>x.Name.Color);
}
静态U测试(表达式表达式表达式),其中U:属性
{
如果(!(expr.Body为MemberExpression memberExpr))
{
抛出新的NotSupportedException(“expr”);
}
返回(U)memberExpr.Member.GetCustomAttribute(typeof(U),false);
}
}

您可以使用
MemberExpression
指定要从中获取属性的成员。以下是一个例子:

using System;
using System.Linq.Expressions;
using System.Reflection;

public class VehicleAttribute : Attribute
{
    public string Color { get; }
    public int NumWheels { get; }

    public VehicleAttribute(string color, int numWheels)
    {
        Color = color;
        NumWheels = numWheels;
    }
}

[Vehicle("Yellow", 6)]
public class Bus
{ 

    [Vehicle("Blue", 5)]
    public string Name { get; set; }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(Test<Bus, VehicleAttribute>((x) => x.Name).Color);
    }

    static U Test<T, U>(Expression<Func<T, object>> expr) where U : Attribute
    {
        if(!(expr.Body is MemberExpression memberExpr))
        {
            throw new NotSupportedException("expr");
        }
        return (U)memberExpr.Member.GetCustomAttribute(typeof(U), false);
    }
}
使用系统;
使用System.Linq.Expressions;
运用系统反思;
公共类车辆属性:属性
{
公共字符串颜色{get;}
public int NumWheels{get;}
公共车辆属性(字符串颜色,整数跟数)
{
颜色=颜色;
NumWheels=NumWheels;
}
}
[车辆(黄色),6)]
公车
{ 
[车辆(蓝色),5)]
公共字符串名称{get;set;}
}
公共课程
{
公共静态void Main()
{
Console.WriteLine(测试((x)=>x.Name.Color);
}
静态U测试(表达式表达式表达式),其中U:属性
{
如果(!(expr.Body为MemberExpression memberExpr))
{
抛出新的NotSupportedException(“expr”);
}
返回(U)memberExpr.Member.GetCustomAttribute(typeof(U),false);
}
}

使用表达式应该可以做到这一点。@Thehenny——目前我的强项之一不是这样。你介意帮我吗?你是说像这里的一般方法:?他们已经存在了一段时间,智能感知应该把他们拉进来。我想我明白你的意思了……就像下面亨利的答案一样。不管怎样,留下我的其他评论。请注意,如果您需要继承的属性,那么他的解决方案将无法处理属性(或事件),因为您必须在这些实例中调用
Attribute.GetCustomAttributes
,而这些实例应该可以使用表达式来实现。@thehenny--目前不是我的强项之一。你介意帮我吗?你是说像这里的一般方法:?他们已经存在了一段时间,智能感知应该把他们拉进来。我想我明白你的意思了……就像下面亨利的答案一样。不管怎样,留下我的其他评论。请注意,如果您需要继承的属性,那么他的解决方案将无法处理属性(或事件),因为您必须在这些实例中调用
Attribute.GetCustomAttributes
using System;
using System.Linq.Expressions;
using System.Reflection;

public class VehicleAttribute : Attribute
{
    public string Color { get; }
    public int NumWheels { get; }

    public VehicleAttribute(string color, int numWheels)
    {
        Color = color;
        NumWheels = numWheels;
    }
}

[Vehicle("Yellow", 6)]
public class Bus
{ 

    [Vehicle("Blue", 5)]
    public string Name { get; set; }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(Test<Bus, VehicleAttribute>((x) => x.Name).Color);
    }

    static U Test<T, U>(Expression<Func<T, object>> expr) where U : Attribute
    {
        if(!(expr.Body is MemberExpression memberExpr))
        {
            throw new NotSupportedException("expr");
        }
        return (U)memberExpr.Member.GetCustomAttribute(typeof(U), false);
    }
}