【问题标题】:Generic Extension method in C# [closed]C#中的通用扩展方法[关闭]
【发布时间】:2017-08-09 04:10:39
【问题描述】:

我有不同的自定义类列表。并且需要检查 String 类型的属性并验证属性的值。如果有一些错误的值,则用一些预定义的值更改该值。 为此,我想创建一个通用方法 公共 IEnumerable 验证(此 IEnumerable ListofData)

但现在我无法遍历属性并检查值并在操作后返回相同的值。 请找到示例代码。

谢谢。

 public static  class ValidateExt
{
   public static IEnumerable<T> ValidateStringData<T>(this IEnumerable<T> DataList)
   {
       PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
       foreach(T Item in DataList)
       {
           // here want to manipulate the date of those properties which is of string type and assign it back.
       }
   }
}

【问题讨论】:

  • 不要粗鲁,但我不认为这是一个问题,听起来像是要求我们做你的研究..
  • 建议您发布一些代码,或者至少是您希望它的行为方式的示例。
  • 对不起,请找到我试过的一些代码。公共静态类 ValidateExt { 公共静态 IEnumerable ValidateStringData(this IEnumerable DataList) { PropertyDescriptorCollection 属性 = TypeDescriptor.GetProperties(typeof(T)); foreach(T Item in DataList) { // 这里要操作那些字符串类型的属性的日期并将其分配回去。 } } }
  • 如果它是针对特定类的,那么它到底是什么通用的?如果我在你的位置,我会在你的自定义类中添加一个名为 ValidateStringData 的方法,并执行类似 myList.ForEach(cc =&gt; cc.ValidateStringData()) 的操作。
  • 它适用于具有大量属性的不同类列表,并且需要更改值,因为它包含一些预定义的文本。

标签: c# generics extension-methods


【解决方案1】:

不确定您将如何对不同的字符串属性使用不同的检查函数(或者您只是对所有字符串属性使用相同的逻辑),但这里是您如何读取所有字符串属性并将它们设置为其他内容的示例如果满足某些条件。

public static IEnumerable<T> ValidateStringData<T>(this IEnumerable<T> dataList)
{
    var properties = typeof(T).GetProperties().Where(p => p.PropertyType == typeof(string)).ToArray();
    foreach (var item in dataList)
    {
        foreach (var propertyInfo in properties)
        {
            var value = propertyInfo.GetValue(item, null) as string;
            string newValue;

            if (CheckString(value, out newValue))
            {
                propertyInfo.SetValue(item, newValue, null);
            }
        }

        yield return item;
    }
}

private static bool CheckString(string value, out string newValue)
{
    // do your validation logic here.
}

【讨论】:

    猜你喜欢
    • 2015-10-02
    • 1970-01-01
    • 2016-10-30
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    相关资源
    最近更新 更多