如何获取通用属性但忽略其类型?

时间:2015-05-05 00:28:31

标签: c# .net generics reflection

我有一个基本上是键值对的结构。我有另一个具有这些MyStruct的多个属性的类(键是字符串,值是T)或其他类型。我想获取所有属性并在值上调用它们的ToString函数,例如

foreach (var prop in AllTheProperties)
{
  if (prop.GetType() is typeof(MyStruct<ignoreMe>)
  {
   yield return prop.Key;
   yield return prop.Value.ToString();
   }
}

但是我被卡住的地方就是打字部分。我不想获得所有类型的字符串,然后输入int等。我怎么能忽略这种类型? (在旁注中,这将被移植到VB,但我更喜欢在c#中做一些事情。)

3 个答案:

答案 0 :(得分:1)

使用此方法。它使用反射和LINQ来调用任何对象数组的所有公共属性的ToString。

    public static IEnumerable<string> GetAllPropsAsStrings(object[] objs)
    {
        return from obj in objs from prop in obj.GetType().GetProperties() select prop.GetValue(obj).ToString();
    }

使用两个不同的keyvaluepairs的示例用法,但这也适用于您自己的自定义结构:

        KeyValuePair<string, int> blah = new KeyValuePair<string, int>("hello", 42);
        KeyValuePair<int, int> blah2 = new KeyValuePair<int, int>(22, 42);

        var stringarray = GetAllPropsAsStrings(new object[] {blah, blah2});
        foreach (string str in stringarray)
        {
            Console.WriteLine(str);
        }

答案 1 :(得分:1)

我会为您的MyStruct<T>对象分配一个属性为string Key且只读属性为object ObjectValue的接口。然后我将在Value属性的实现中返回ObjectValue。这是一个例子:

public interface GenericMyStruct
{
    string Key { get; set; }

    object ObjectValue { get; }
}

public class MyStruct<T> : GenericMyStruct
{
    public string Key { get; set; }

    public T Value { get; set; }

    public object ObjectValue { get { return (object)Value; } }
}

您写出所有属性的代码看起来像这样:

foreach (var prop in AllTheProperties)
{
    if (prop is GenericMyStruct)
    {
        yield return prop.Key;
        yield return prop.ObjectValue.ToString();
    }
}   

答案 2 :(得分:1)

如果你所追求的是确保所使用的泛型类型是MyStruct而不管T,那么你必须只比较泛型类型定义。

Type propType = prop.GetType();
if(propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(MyStruct<>))
            {
             //Do work
            }

如果MyStruct类型的对象与泛型类型参数无关,则它将始终返回true。

信用: - How to get base class's generic type parameter?

相关问题