「Unity/Csharp/クラス/ジェネリックインターフェース」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==ジェネリックインターフェースのサンプル== ===ジェネリック内で、リフレクションを取得パターン=== 呼び出し処理 LoadDialog...」) |
(→parameters.GetType().GetProperty()が取得できないとき) |
||
(同じ利用者による、間の4版が非表示) | |||
行15: | 行15: | ||
public interface ILoadDialogDelegate | public interface ILoadDialogDelegate | ||
{ | { | ||
− | void LoadDialog<TParams>(TParams parameters); | + | void LoadDialog<TParams>(TParams parameters) where TParams : class; |
} | } | ||
</pre> | </pre> | ||
行26: | 行26: | ||
public class LoadDialogUseCase : ILoadDialogDelegate | public class LoadDialogUseCase : ILoadDialogDelegate | ||
{ | { | ||
− | public void LoadDialog<TParams>(TParams parameters) | + | public void LoadDialog<TParams>(TParams parameters) where TParams : class |
{ | { | ||
var prop = parameters.GetType().GetProperty("TimeId"); | var prop = parameters.GetType().GetProperty("TimeId"); | ||
行58: | 行58: | ||
} | } | ||
</pre> | </pre> | ||
+ | |||
+ | ==parameters.GetType().GetProperty()が取得できないとき== | ||
+ | 例として、以下がnullになるとき | ||
+ | if (parameters.GetType().GetProperty("CloseEvent") == null) { | ||
+ | 以下のget;があるか確認。 | ||
+ | public Action CloseEvent { get; } | ||
+ | setもしたいときはこちら。 | ||
+ | public Action CloseEvent { get; set; } |
2025年5月13日 (火) 02:18時点における最新版
ジェネリックインターフェースのサンプル
ジェネリック内で、リフレクションを取得パターン
呼び出し処理
LoadDialogの引数に、色々なクラスを、入れることができる。
var timeDetailDialogParams = new TimeDetailDialogParams(1, () => { Debug.Log("Close"); }); var loadDialogUseCase = new LoadDialogUseCase(); loadDialogUseCase.LoadDialog(timeDetailDialogParams);
ILoadDialogDelegate.cs
public interface ILoadDialogDelegate { void LoadDialog<TParams>(TParams parameters) where TParams : class; }
LoadDialogUseCase.cs
using System; using UnityEngine; public class LoadDialogUseCase : ILoadDialogDelegate { public void LoadDialog<TParams>(TParams parameters) where TParams : class { var prop = parameters.GetType().GetProperty("TimeId"); if (prop != null) { int timeId = (int)prop.GetValue(parameters); Debug.Log($"TimeId: {timeId}"); } var closeEventProp = parameters.GetType().GetProperty("CloseEvent"); if (closeEventProp != null) { var closeAction = closeEventProp.GetValue(parameters) as Action; closeAction?.Invoke(); } } }
TimeDetailDialogParams.cs
public class TimeDetailDialogParams { public int TimeId { get; } public Action CloseEvent { get; } public TimeDetailDialogParams(int timeId, Action closeEvent) { TimeId = timeId; CloseEvent = closeEvent; } }
parameters.GetType().GetProperty()が取得できないとき
例として、以下がnullになるとき
if (parameters.GetType().GetProperty("CloseEvent") == null) {
以下のget;があるか確認。
public Action CloseEvent { get; }
setもしたいときはこちら。
public Action CloseEvent { get; set; }