繁体   English   中英

如何将泛型类型参数传递给从构造函数调用的方法?

[英]How do I pass a generic type parameter to a method called from a constructor?

这是构造函数:

 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,它给了我运行时错误:无法找到类型或命名空间'T'...

我如何(a)正确分配T,或(b)通过构造函数传递泛型? 我一直在查看相当多的帖子,但可能由于缺乏理解而遗漏了一些内容。 任何人对此的帮助将不胜感激。

你的班级必须是通用的。 所以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);
    }
}

创建泛型类,其中泛型类型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
     }

}

如果你静态知道_FirstRole的类型(是PartyRole吗?),你可以使用它:

_SecondRole.ProvisionRelationship<PartyRole>(_FirstRole);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM