2015-02-15 2 views
-3

Мне нужно реализовать этот метод: Reflectable reflect<T>(IEnumerable<T> src) , но у меня возникают проблемы, чтобы получить ожидаемый результат. Надеюсь, кто-то может мне помочь.Внедрение метода расширения C#

Здесь интерфейс Reflectable:

interface Reflectable : IEnumerable<string> { Reflectable Prop(string propName);}

и ожидаемый выход:

IEnumerable<Student> stds = //Students 
IEnumerable<String> r1 = reflect(stds).Prop("Id"); 
IEnumerable<String> r2 = reflect(stds).Prop("Name").Prop("Id").Prop("Age"); 
IEnumerable<String> r3 = reflect(stds); 
r1.ToList().ForEach(Console.Write); // {3213}{3124}{35454}... 
r2.ToList().ForEach(Console.Write); // {Jose, 3213, 89}{Maria, 3124, 34}{Prominencia, 35454, 23}... 
r3.ToList().ForEach(Console.Write); // {}{}{}... 
+0

мне нужно реализовать метод отражения, чтобы получить выход в комментарии но я не знаете, как. –

+1

Как вы думаете, что такое «метод расширения»? Потому что я не могу это заметить. –

+0

Я думаю, что Prop() - метод расширения Reflect –

ответ

1

Я все еще думаю, что эта ваша мысль должна быть убита во сне, или до рождения ...

public class ReflectionHelper<T> 
    : IEnumerable<string> 
{ 
    private string[] _properties; 
    private IEnumerable<T> _list; 

    public ReflectionHelper(IEnumerable<T> list, string[] properties) 
    { 
     _properties = properties; 
     _list = list; 
    } 

    public ReflectionHelper<T> Prop(string property) 
    { 
     return new ReflectionHelper<T>(_list, _properties.Concat(new string[]{ property}).ToArray()); 
    } 

    public ReflectionHelper<T> Prop(string property) 
    { 
     return new ReflectionHelper<T>(_list, _properties.Concat(new string[] { property }).ToArray()); 
    } 

    public static implicit operator List<string>(ReflectionHelper<T> helper) 
    { 
     return helper._list.Select(item => string.Join(",", 
         (from p in helper._properties 
         select typeof(T).GetProperty(p).GetValue(item, null)).ToArray())).ToList(); 
    } 

    public IEnumerator<string> GetEnumerator() 
    { 
     return _list.Select(item => string.Join(",", 
               (from p in _properties 
               select typeof (T).GetProperty(p).GetValue(item, null)).ToArray())) 
        .GetEnumerator(); 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); 
    } 
} 

public static class ReflectionHelperExtension 
{ 
    public static ReflectionHelper<T> Prop<T>(this IEnumerable<T> items, string property) 
    { 
     return new ReflectionHelper<T>(items, new string[] { property }); 
    } 
} 
+0

Я получаю некоторую ошибку времени компиляции в VS на вашем коде. вы его проверяете? – dovid

+0

@lomed Обновлено ... pff ... было почти правильно ...> _ < – Aron

+0

100%. лучший код, спасибо. – dovid

1

Если я понимаю, что вы достижения, методы расширения будет способ сделать это, и вот так:

// This class has to be static for extension methods to be detected 
public static class MyExtensions 
{ 
    // using "this" before the first parameter will make it an extension of the type 
    public static IEnumerable<string> Prop<T>(this IEnumerable<T> enumerable, string propName) 
    { 
     var type = typeof(T); 
     // Note that this can throw an exception if the property is not found 
     var info = type.GetProperty(propName); 

     // Here are your students, considering that <T> is <Student> 
     foreach (var item in enumerable) 
     { 
      // return the value fromt the item, I'm using ToString here for 
      // simplicity, but since you don't know the property type in 
      // advance, you can't really do anything else than assumne its 
      // type is plain "object" 
      yield return info.GetValue(item).ToString(); 
     } 
    } 
} 

Одна вещь, которую вы не будете b что можно сделать, это связать их, как сказал @lomed, поскольку он возвращает IEnumerable.

0
public static class EnumerableReflect 
{ 
    private static string OneElementReflect<T>(T e, PropertyInfo[] props) 
    { 
     var values = props.Select(x => x.GetValue(e).ToString()); 
     return "{" + string.Join(", ", values)) + "}"; 
    } 

    public static IEnumerable<string> enumerbleString<T>(this IEnumerable<T> collection, params string[] PropertysNames) 
    { 
     var props = PropertysNames.Select(x => typeof(T).GetProperty(x)).ToArray(); 
     return collection.Select(x => OneElementReflect(x, props)); 
    } 
} 
+0

спасибо, что вы меня спасли –

Смежные вопросы