0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

プロパティとしてのクラス(Table Per Type編)0

Last updated at Posted at 2022-02-24

EntityFrameworkで設計していると
「この項目、外部からはプロパティとして動作してほしいけど、内部的には別クラスのインスタンスとして実装したいな」と考えることがある。
そこでIDと値だけのジェネリックインターフェイスを定義してみる。

IClassAsProperty.cs
    public interface IClassAsProperty<T> where T : struct
    {
        public T value { get; set; }
    }

でクラスをプロパティとして扱うにはジェネリック静的プロパティを定義する。

ClassAsProperty.cs
    public static class ClassAsProperty
    {

        public static T? GetmethodT<T, T2>(ref T2 TargetPoperty) where T : struct where T2 : IClassAsProperty<T>
        {
            return TargetPoperty?.value;
        }

        public static void setMetgidT<T, T2>(T value, ref T2 TargetProperty) where T : struct where T2 : IClassAsProperty<T>, new()
        {
            if (TargetProperty is null)
            { TargetProperty = new T2(); }
            TargetProperty.value = value;
        }
    }

何をしているかというと
getメソッド時にはnull許容型にしておいてnullであればnullを返すようにする。
setメソッド時にはnullであれば新規インスタンスを生成して値を格納するとする。
実際の使い方は次回で

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?