gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:58:29 26 4
gpt4 key购买 nike

这是构造函数:

 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) 使用构造函数传递通用类型?我一直在浏览很多帖子,但由于缺乏理解,可能遗漏了一些东西。任何人对此的帮助将不胜感激。

最佳答案

您的类(class)需要通用。所以 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);
}
}

关于c# - 如何将泛型类型参数传递给从构造函数调用的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com