[英]Returning object attributes from C# function to Blazor web elements
我试图在 C# 中初始化一个新对象,然后将新创建的对象的属性打印到<p>
标记中。 我被困在如何从以下位置获取生成的对象:
<button type="button" @onclick="@(() => createSword("steel"))">
And being able to use it in my web app.
@page "/authors"
<h3>Authors</h3>
<button type="button" @onclick="@(() => createSword("steel"))">Click me to generate a new sword</button>
<p> Current Sword: </p> <p id="generatedSword">My Sword Details here</p>
@{ <p> Hello </p>
}
@code {
public Object createSword(string x)
{
Sword testSword = new Sword(x);
return testSword;
}
public class Sword
{
//Defining attributes of sword
public int damage;
public String statType;
public int stat;
public String name;
//Defining private variables of sword
public Sword(string typeOfSword)
{
if (typeOfSword == "Steel")
{
damage = 5;
name = "Steel Sword";
statType = "Strength";
stat = 2;
}
if (typeOfSword == "Bone")
{
damage = 10;
name = "Bone Sword";
statType = "Strength";
stat = 5;
}
if (typeOfSword == "Glowing")
{
damage = 20;
name = "Glowing Sword";
statType = "Strength";
stat = 10;
}
if (typeOfSword == null)
{
damage = 1;
name = "None";
statType = "None";
stat = 0;
}
}
}
}
在这样做之前我是否必须将它分配给一个全局对象? 我相信这可以在我创建播放器类时规避,我可以在这些字段中打印播放器数据,因为播放器对象将是一个唯一的持久对象。 想法?
这是否回答了您的问题(似乎太简单了)?
我已将您的剑类型更改为emun
,并将对象创建者作为静态方法添加到Sword
类。
创建的对象位于私有字段generatedSword
。
@page "/"
<h3>Authors</h3>
<button type="button" @onclick="() => CreateSword(Sword.SwordType.Steel)">Click me to generate a new sword</button>
@if (generatedSword != null)
{
<p> Current Sword: @generatedSword.name</p>
}
@{
<p> Hello </p>
}
@code {
private Sword generatedSword;
private void CreateSword(Sword.SwordType typeOfSword)
=> generatedSword = Sword.NewSword(typeOfSword);
public class Sword
{
//Defining attributes of sword
public int damage;
public String statType;
public int stat;
public String name;
//Defining private variables of sword
public Sword(SwordType typeOfSword)
{
if (typeOfSword == SwordType.Steel)
{
damage = 5;
name = "Steel Sword";
statType = "Strength";
stat = 2;
}
if (typeOfSword == SwordType.Bone)
{
damage = 10;
name = "Bone Sword";
statType = "Strength";
stat = 5;
}
if (typeOfSword == SwordType.Glowing)
{
damage = 20;
name = "Glowing Sword";
statType = "Strength";
stat = 10;
}
if (typeOfSword == SwordType.None)
{
damage = 1;
name = "None";
statType = "None";
stat = 0;
}
}
public enum SwordType {None, Steel, Bone, Glowing};
public static Sword NewSword(SwordType typeOfSword)
=> new Sword(typeOfSword);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.