9

コンストラクタは次のとおりです。

 public PartyRoleRelationship(PartyRole firstRole, PartyRole secondRole)
        {
            if (firstRole == secondRole)
                throw new Exception("PartyRoleRelationship cannot relate a single role to itself.");

            if (firstRole.OccupiedBy == null || secondRole.OccupiedBy == null)
                throw new Exception("One or both of the PartyRole parameters is not occupied by a party.");

            // Connect this relationship with the two roles.
            _FirstRole = firstRole;
            _SecondRole = secondRole;


            T = _FirstRole.GetType().MakeGenericType();

            _SecondRole.ProvisionRelationship<T>(_FirstRole); // Connect second role to this relationship.
        }

_SecondRole で ProvisionRelationship を呼び出す最後の行で、実行時エラーが発生します: Type or namespace 'T' could not be found...

(a) T を適切に割り当てるか、(b) コンストラクターでジェネリック型を渡すにはどうすればよいですか? かなりの数の投稿に目を通しましたが、理解不足のために何かを見落としている可能性があります。これに関する誰の助けも大歓迎です。

4

3 に答える 3

14

クラスはジェネリックである必要があります。したがってPartyRoleRelationship、次のようにする必要があります。

public class PartyRoleRelationship<T>
{
    public PartyRoleRelationship(T arg, ...)
    {
    }
}

ジェネリック クラスの詳細については、こちらをご覧ください。

http://msdn.microsoft.com/en-us/library/sz6zd40f(v=vs.80).aspx

http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx

編集:

おそらく、コードを少し単純化して、次のようにすることができます。

public class RoleRelationship<T>
{
    public RoleRelationship(T firstRole, T secondRole)
    {
        if (firstRole.OccupiedBy == null || secondRole.OccupiedBy == null)
            throw new Exception("One or both of the Role parameters is not occupied by a party.");

        // Connect this relationship with the two roles.
        _FirstRole = firstRole;
        _SecondRole = secondRole;

        _SecondRole.ProvisionRelationship<T>(_FirstRole);
    }
}
于 2013-03-03T22:59:26.407 に答える
4

ジェネリック型Tが基本クラスPartyRoleの型であるジェネリッククラスを作成します。

public class PartyRoleRelationship<T> where T : PartyRole 
{
     T _FirstRole;
     T _SecondRole;

     public PartyRoleRelationship(T role1, T role2) {
         _FirstRole = role1;
         _SecondRole = role2;
         role1.ProvisionRelationship(role2)
     }

     public ProvisionRelationship(T otherRole) {
          // Do whatever you want here
     }

}
于 2013-03-03T23:15:54.803 に答える
0

_FirstRole のタイプが静的にわかっている場合 (PartyRole ですか?)、それをそのまま使用できます。

_SecondRole.ProvisionRelationship<PartyRole>(_FirstRole);
于 2013-03-03T22:59:52.520 に答える