zoukankan      html  css  js  c++  java
  • Extension Method的两个小例子(Dictionary_FindKeyByValue && T_Clone)

    直接上代码了,以后碰到类似的就直接用了

    public static TKey FindKeyByValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TValue value)
    {
    if (dictionary == null)
    throw new ArgumentNullException("dictionary");

    foreach (KeyValuePair<TKey, TValue> pair in dictionary)
    if (value.Equals(pair.Value)) return pair.Key;

    throw new Exception("the value is not found in the dictionary");
    }

      public static T Clone<T>(this T source)
    {
    T Cloned = (T)Activator.CreateInstance(source.GetType());

    (from Property in source.GetType().GetProperties()

    where Property.GetGetMethod() != null && Property.GetSetMethod() != null
    select Property).ToList().ForEach(Property =>
    {
    // Check if the object inherits from ICollection (The ICollection interface is the base interface for classes in the System.Collections namespace
    if (!Property.PropertyType.GetInterfaces().Contains(typeof(ICollection)))
    {
    object PropertyValue = Property.GetGetMethod().Invoke(source, Property.GetGetMethod().GetParameters());

    if (PropertyValue != null && PropertyValue is DependencyObject) { PropertyValue = PropertyValue.Clone(); }

    // if PropertyValue is not a value type and is itself a dependency object, it must be "cloned" as well
    Property.GetSetMethod().Invoke(Cloned, new object[] { PropertyValue });
    }
    else if (Property.PropertyType.GetInterfaces().Contains(typeof(ICollection)))
    {
    ICollection CollectionValue = (ICollection)Property.GetGetMethod().Invoke(source, new object[] { }); Property.SetValue(Cloned, CollectionValue, null);
    }

    });
    return Cloned;
    }



  • 相关阅读:
    排序_简单选择排序
    排序_冒泡排序
    笔试_阿里_逆波兰表达式
    刷题_牛客_大整数排序
    刷题_牛客_字符串编码
    刷题_thinkinginjava_吸血鬼数字
    刷题_牛客_超级素数幂
    刷题_LeetCode_Two Sum
    刷题_LeetCode_Reverse Integer
    854. Floyd求最短路(模板)
  • 原文地址:https://www.cnblogs.com/leon032/p/2295459.html
Copyright © 2011-2022 走看看