0

Windows CE デバイスの ORM に取り組んでいます。プロパティの getter/setter メソッドをデリゲートとしてキャッシュし、最適なパフォーマンスを得るために必要なときに呼び出す必要があります。

次のように定義された 2 つのエンティティがあるとします。

public class Car
{
    public string Model { get; set; }
    public int HP { get; set; }
}

public class Driver
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}

各エンティティのプロパティごとに 2 つのデリゲートを保持できる必要があります。そこで、プロパティごとに 2 つのデリゲートを保持する AccessorDelegates クラスを作成します。

 public class AccessorDelegates<T>
{
    public Action<T, object> Setter;
    public Func<T, object> Getter;

    public AccessorDelegates(PropertyInfo propertyInfo)
    {
        MethodInfo getMethod = propertyInfo.GetGetMethod();
        MethodInfo setMethod = propertyInfo.GetSetMethod();

        Setter = BuildSetter(setMethod, propertyInfo); // These methods are helpers
        Getter = BuildGetter(getMethod, propertyInfo); // Can be ignored
    }
}

次に、特定のエンティティ タイプの各 AccessorDelegates をリストに追加します。だから私はクラスを定義しました:

public class EntityProperties<T>
{
    public List<AccessorDelegates<T>> Properties { get; set; }
}

この例の Car と Driver では、エンティティ タイプごとにこれらの EntityProperties を保持する必要があります。Dictionary<string, EntityProperties<T>>ここでは、簡単にするために、エンティティ名を表す文字列を作成しました。

public class Repo<T>
{
    public Dictionary<string, EntityProperties<T>> EntityPropDict { get; set; }
}

これは、私の問題の解決策を見つけることができない場所です。EntityPropertiesエンティティ型ごとに保持したいのですがRepo<T>、辞書を作成できるようにするには、クラスに型パラメーターを指定する必要があります (型パラメーターEntityProperties<T>が必要なため)。

型パラメーターなしでのみ作成できるようにする必要がありますRepoDictionary<string, EntityProperties<T>>Repo クラスに型パラメーターを指定せずに を定義するにはどうすればよいですか?

4

1 に答える 1

0

少しスマートなコードですが、問題なく動作します。

AccessorDelegates によって実装されるインターフェイスを追加しました。

public interface IAccessorDelegates
{
    void Init(PropertyInfo propertyInfo);
}

AccessorDelegate の代わりに IAccessorDelegate を含むように PropertyMetadata を変更しました。

public class PropertyMetadata
{
    public PropMapAttribute Attribute { get; set; }
    public PropertyInfo PropertyInfo { get; set; }
    public IAccessorDelegates AccessorDelegates { get; set; }

    public PropertyMetadata()
    {

    }

    public PropertyMetadata(PropMapAttribute attribute, PropertyInfo propertyInfo, IAccessorDelegates delegates)
    {
        Attribute = attribute;
        PropertyInfo = propertyInfo;
        AccessorDelegates = delegates;
    }

    public AccessorDelegates<T> GetAccesssorDelegates<T>()
    {
        return (AccessorDelegates<T>)AccessorDelegates;
    }
}

これで、次の方法で AccessorDelegate を作成して初期化できます。

 Type accesssorType = typeof(AccessorDelegates<>);
 Type genericAccessorType = accesssorType.MakeGenericType(type);
 IAccessorDelegates accessor = (IAccessorDelegates)Activator.CreateInstance(genericAccessorType);
 accessor.Init(propertyInfo);

PropertyMetadata.GetAccessorDelegates<T>()AccessorDelegate<T>メソッドを使用すると、実際の型でオブジェクトをキャストして取得できます。

于 2013-01-30T11:57:38.650 に答える