理解泛型类实现

  • 本文关键字:实现 泛型类 c# generics
  • 更新时间 :
  • 英文 :


我正在努力理解以下代码:

public interface IBuilding
{
string Id { get; }
}
public class Model<TBuilding>
where TBuilding : IBuilding
{
public TBuilding Building { get; private set; }
}

Model<TBuilding>在这里是什么意思?根据我的理解,ClassName<T>代表泛型类。<T>可以表示字符串、int等,但<TBuilding>在这里实现了IBuilding接口。为什么泛型类型实现接口?我怀疑<T>的意思是<Id>。我说得对吗?

我不知道如何理解这个代码。我读过泛型类,但找不到任何有用的东西。

不完全是。T只是一个类型的占位符。如果您有实现IBuildingFireHousePoliceStationHospital等,则可以将其中一个提供给Model,并且Building属性将只包含该类型的实例。

命名有点误导

public interface IBuilding // interface contract
{
string Id { get; }
string ElevatorCount { get; }
}
// this is where you have confusion. T - is standard naming for generic type parameter
// if you start naming your generic type parameter TBuilding - 
// you will get confused that it might be some type
public class BuildingInspector<T>  where T : IBuilding // T : IBuilding - restricts types to IBuilding
{
public BuildingInspector(T building) // generic type in constructor
{
Building = building;
}
public T Building { get; private set; }
public int GetTotalElevatorCapacity(int kiloPerElevator)
{
return (this.Building.ElevatorCount * kiloPerElevator)  
}
}
// U S A G E
public class SingleFamilyHome : IBuilding
{
public string Id { get; private set; }
public string ElevatorCount { get; private set; }
}
. . . . .
private void TryUsingGenericType ()
{
var famHome = new SingleFamilyHome(){ Id=1, ElevatorCount=0 };
var famInspector = new BuildingInspector<SingleFamilyHome>(); // SUCCESS
var capacity = famInspector.GetTotalElevatorCapacity(0);
// this code will not compile because above you have --> where T : IBuilding
var stringInspector = new BuildingInspector<string>(); // DESIGN TIME ERROR
}

现在您看到了声明AND的用法,您可以看到它是如何使用的。最好的例子是System.Collections.Generic.List<T>。你可以有任何列表

List<string>
List<Building>
List<int>

‘此处’语法将T类型约束为实现IBuilding的类型。如果没有where条件,它将接受任何类型。在这里你可以找到更详细的解释。https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint

最新更新