[英]Generic Razor Type Parameter pass as variable
Razor/Blazor component with Generic Type Parameter as a variable使用通用类型参数作为变量的 Razor/Blazor 组件
<QueryRow Titem="Person"/>
Works作品
in the above component i can recieve the parameter在上述组件中,我可以接收参数
Type typeParameterType = typeof(Titem);
and create an instance并创建一个实例
object? myObject = Activator.CreateInstance(typeParameterType);
That all works great, however然而,这一切都很好
public Type mytype = typeof(Person);
<QueryRow Titem="@mytype"/>
Does not work, I need be able to pass the types down from the parent as list of types or strings I can convert to real types using reflection.不起作用,我需要能够将类型从父级作为类型或字符串列表向下传递,我可以使用反射将其转换为真实类型。
How do I pass the type parameter as a variable such as如何将类型参数作为变量传递,例如
mytype = typeof(Person);
I can do all this in code but not in razor!!!我可以用代码做所有这些,但不能用剃须刀!!! what am I doing different/ wrong ?
我在做什么不同/错误?
for example, Person starts as a string below例如, Person 以下面的字符串开头
Type? typeArgument = Type.GetType("Person");
Type genericClass = typeof(QueryRow<>);
Type constructedClass = genericClass.MakeGenericType(typeArgument);
object? createdType = Activator.CreateInstance(constructedClass);
works great, but then I have to use blazor's Dynamic component as a workaround to do the render, which I'd rather avoid as it seems a bit yuk效果很好,但是我必须使用 blazor 的 Dynamic 组件作为解决方法来进行渲染,我宁愿避免这样做,因为它看起来有点 yuk
You can't use a variable as the type parameter in this way.您不能以这种方式将变量用作类型参数。
You can create a RenderFragment using a bit of reflection:您可以使用一点反射来创建 RenderFragment:
public Type myType = typeof(Person);
@MakeQueryComponent(myType)
@code {
RenderFragment MakeQueryComponent(Type typeParam)
{
var genericType = typeof(QueryRow<>)
.MakeGenericType(new[] { typeParam });
RenderFragment frag = new RenderFragment(b =>
{
b.OpenComponent(1, genericType);
b.CloseComponent();
});
return frag;
}
}
UPDATE更新
Following GitHub issue 26781 , the Blazor team have now encapsulated the above method of generating a RenderFragment into a new component called DynamicComponent.在GitHub 问题 26781之后,Blazor 团队现在已将上述生成 RenderFragment 的方法封装到一个名为 DynamicComponent 的新组件中。
See source code and guidance .请参阅源代码和指南。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.