#author("2022-05-21T17:30:24+08:00","default:Admin","Admin") #author("2023-03-28T16:13:00+08:00","default:Admin","Admin") [[+C#+言語セクション]] #contents * ジェネリッククラス [#yfbfd7cf] ジェネリッククラスの定義[[VB.NET版>+VB.NET+ジェネリック]] #codeprettify{{ class MyGenericClass1<T> where T : struct { // 制約:Tは構造体 } }} #codeprettify{{ class MyGenericClass2<T> where T : class { // 制約:Tはクラス } }} #codeprettify{{ class MyGenericClass3<T> where T : new() { // 制約:Tはインスタンス化可能 } }} #codeprettify{{ class MyGenericClass4<T> where T : MyOtherClass { // 制約:TはMyOtherClassクラスを継承 } }} #codeprettify{{ class MyGenericClass5<T> where T : IMyInterface { // 制約:TはIMyInterfaceインターフェイスを実装 } }} #codeprettify{{ class MyGenericClass6<T, U> where T : U { // 制約:Tは別の型パラメータUを継承 } }} #codeprettify{{ class MyGenericClass7<T, F> : IDisposable where T : MyOtherClass<F>, IDisposable, new() where F : class { // 制約:T,Fは別々のクラス } }} #codeprettify{{ class MyOtherClass { // あるクラス } }} #codeprettify{{ interface IMyInterface { // あるインターフェイス } }} * ジェネリックメソッド [#i9646ef7] #codeprettify{{ void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T> { T temp; if (lhs.CompareTo(rhs) > 0) { temp = lhs; lhs = rhs; rhs = temp; } } }} return #codeprettify{{ public static T LoadFromXml<T>(string fileName, bool loggingEnabled) where T : class { FileStream fs = null; try { var serializer = new XmlSerializer(typeof(T)); fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); //反序列化对象 return (T)serializer.Deserialize(fs); } catch (Exception e) { if (loggingEnabled) { //文件异常,写入日志 LogLoadFileException(fileName, e); return null; } else { throw new Exception(e.Message); } } finally { if (fs != null) fs.Close(); } } }} #hr(); コメント: #comment_kcaptcha