我有一些条件,当我有一些类列表时,比如List<Crews>
和List<CrewsOnLeave>
,我制作了一些组件,在那里我将使用那里的逻辑,并只发送这两个组件中的一个(CrewsOnLeave或Crews(,所以我不需要在组件中声明我的类,因为这是我的代码
我的代码现在
@using Models.BookingCrew
@if (CrewonLeave.Count() > 0)
{
<td @onclick="SearchCrews">
<span style="cursor: pointer;" data-toggle="modal"
data-target="#@(modalId)">
@CrewonLeave.Count()</span>
</td>
}
else if(Crews.Count()> 0 )
{
<td @onclick="SearchOnLeave">
<span style="cursor: pointer;" data-toggle="modal"
data-target="#@(modalId)">
@Crews.Count()</span>
</td>
}
else
{
<td> </td>
}
@code{
[Parameter]
public string modalId{get;set;}
[Parameter]
public List<Crew> Crews{get; set;}
[Parameter]
public List<CrewOnLeave> CrewonLeave{get;set;}
[Parameter]
public EventCallback<List<CrewOnLeave>> OnLeaveClicked {get; set;}
[Parameter]
public EventCallback<List<Crew>> OnCrewsClicked {get; set;}
private Task SearchCrews()
{
return OnCrewsClicked.InvokeAsync(Crews);
}
private Task SearchOnLeave()
{
return OnLeaveClicked.InvokeAsync(CrewonLeave);
}
}
我的目标是让我的代码像一样更简单
代码目标
@if (Crews.Count() > 0)
{
<td @onclick="SearchCrews">
<span style="cursor: pointer;" data-toggle="modal"
data-target="#@(modalId)">
@Crews.Count()</span>
</td>
}
else
{
<td> </td>
}
@code{
[Parameter]
public string modalId{get;set;}
[Parameter]
public List<DynamicClass> Crews{get; set;}
[Parameter]
public EventCallback<List<DynamicClass>> OnCrewsClicked {get; set;}
private Task SearchCrews()
{
return OnCrewsClicked.InvokeAsync(DynamicClass);
}
}
问题是我不知道如何放入dynamic class
中,所以当组件由带有类的变量列表输入时,类将是动态的。
有什么办法把它做成那样吗?
这一切都取决于CrewOnLeave
和Crew
之间的关系。如果它们不是同一基类的两个化身,那么您需要定义一个两者共享的接口。在该示例中,界面为空白,但仍然有效。
下面是您代码的简化版本,用于演示处理接口到类和类到接口转换的各种方法。
@page "/Crewzing"
<table>
<tr>
@if (_hasCrews)
{
<td @onclick="SearchCrews">
<span style="cursor: pointer;" data-toggle="modal"
data-target="#@(modalId)">
@Crews.Count()
</span>
</td>
}
else
{
<td></td>
}
</tr>
</table>
@code {
public List<ICrew> Crews => CrewsOnLeave.Count > 0 ? CrewsOnLeave.Select(item => (ICrew)item).ToList() : CrewsOnBoard.Select(item => (ICrew)item).ToList();
[Parameter] public EventCallback<List<ICrew>> CrewsClicked { get; set; }
private bool _hasCrews => (this.Crews != null && this.Crews.Count > 0);
private string modalId = "xxx";
private void SearchCrews()
{
GetCrewType();
CrewsClicked.InvokeAsync(Crews);
}
public interface ICrew
{
}
public class CrewOnBoard : ICrew
{
public string Boat { get; set; }
}
public class CrewOnLeave : ICrew
{
public string Boat { get; set; }
}
public List<CrewOnBoard> CrewsOnBoard = new List<CrewOnBoard>()
{
new CrewOnBoard() { Boat = "Cyclops"},
new CrewOnBoard() { Boat = "Sirius"}
};
public List<CrewOnLeave> CrewsOnLeave = new List<CrewOnLeave>()
{
new CrewOnLeave() { Boat = "Medusa"},
new CrewOnLeave() { Boat = "Alderbaran"}
};
private void GetCrewType()
{
var c = Crews[0] ?? null;
if (c is CrewOnBoard)
{
var crew = Crews.Select(item => (CrewOnBoard)item).ToList();
}
else if (c is CrewOnLeave)
{
var crew = Crews.Select(item => (CrewOnLeave)item).ToList();
}
}
}