終極方案:單一 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) { ... }
}
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> 入口,智能提示僅顯示群組入口