首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 擴展方法進階技巧:擴展方法分組管理動態實作 (下)

     編輯:關於C語言

終極方案:單一 As<T>() 擴展 + 介面分組 + 反射發射動態實作。定義空介面標記擴展群組,As<T>() 依介面動態建立實作類別。

介面與擴展群組定義

public interface IConvertableString : IExtension<string> { }
public static class ConvertableString {
    public static bool IsInt(this IConvertableString s) { ... }
    public static DateTime ToDateTime(this IConvertableString s) { ... }
}

public interface IRegexableString : IExtension<string> { }
public static class RegexableString {
    public static bool IsMatch(this IRegexableString s, string pattern) { ... }
}

核心機制:IExtension<V> + 動態型別建立

public interface IExtension<V> { V GetValue(); }

public static class ExtensionGroup {
    private static Dictionary<Type, Type> cache = new Dictionary<Type, Type>();
    
    public static T As<T>(this string v) where T : IExtension<string> 
        => As<T, string>(v);
    
    public static T As<T, V>(this V v) where T : IExtension<V> {
        Type t = cache.GetOrAdd(typeof(V), _ => CreateType<T, V>());
        return (T)Activator.CreateInstance(t, v);
    }
    
    private static Type CreateType<T, V>() where T : IExtension<V> {
        // 使用 Reflection.Emit 動態建立實作 T 介面的類別
        // 包含私有 value 欄位、建構子、GetValue() 實作
    }
}

優勢

  • 單一 As<T> 入口,智能提示僅顯示群組入口
  • 擴展方法定義在介面上,語意清晰
  • 動態發射避免手寫包裝類別
  • 快取機制確保效能
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved