在这种情况下,var 的类型是什么?

What is the Type of var in this case?

我偶然发现了这个 post 关于 C# 中的反射。我的想法是从中创建一个辅助方法,以便在我的代码中的多个地方使用它。但是我不知道该方法应该有什么 return 类型。 IDE 显示类型 local variable IEnumerable<{PropertyInfo Property, T Attribute}> properties 但这不被接受为方法的 return 类型。

这是我当前的代码,显然不起作用。

public static IEnumerable<PropertyInfo, T> GetPropertiesAndAttributes<T>(object _instance, BindingFlags _bindingFlags = FULL_BINDING) where T : Attribute
    {
        var properties = from p in _instance.GetType().GetProperties(_bindingFlags)
            let attr = p.GetCustomAttributes(typeof(T), true)
            where attr.Length == 1
            select new { Property = p, Attribute = attr.First() as T};

        return properties;
    }

哪种 return 类型可以使此方法发挥作用?

谢谢!

在您当前的代码中,您正在尝试 return 匿名类型:

 new { Property = p, Attribute = attr.First() as T};

你可以把它变成命名元组稍作改动:

public static IEnumerable<(PropertyInfo p, T Attribute)> GetPropertiesAndAttributes<T>(
  object _instance, 
  BindingFlags _bindingFlags = FULL_BINDING) where T : Attribute
{
    var properties = from p in _instance.GetType().GetProperties(_bindingFlags)
        let attr = p.GetCustomAttributes(typeof(T), true)
        where attr.Length == 1
        select (p, attr.First() as T);

    return properties;
}

这将创建一个匿名对象:

new { Property = p, Attribute = attr.First() as T }

匿名类型是由编译器生成的,所以你不能声明一个return是匿名类型的方法;它们只能存在于本地范围内。

如果您想 return 枚举,您可以使用 ValueTuple 作为项目类型:

public static IEnumerable<(PropertyInfo Property, T Attribute)> GetPropertiesAndAttributes<T>(
    object _instance, BindingFlags _bindingFlags = FULL_BINDING)
where T : Attribute
{
    var properties = from p in _instance.GetType().GetProperties(_bindingFlags)
        let attr = p.GetCustomAttributes(typeof(T), true)
        where attr.Length == 1
        select (Property: p, Attribute: attr.First() as T);

    return properties;
}