Blazor-Component สืบทอดมาจาก BaseClass

Sep 29 2020

ฉันกำลังจะสร้าง Base-Class สำหรับ Razor-Components ของฉัน Base-Class นี้มีลักษณะดังนี้:

public abstract class ExampleBase : ComponentBase 
{
    public virtual void Submit()
    {
        //DoSomething
    }

    public virtual void Back()
    {
        //DoSomething else
    }
}

Blazor-Component ของฉันสืบทอดมาจากคลาสนี้

@inherits ExampleBase

<button @onclick="Submit" />

จนถึงตอนนี้ดีมาก แต่เมื่อฉันเริ่มแอพและหน้านี้กำลังจะโหลดฉันจะได้รับข้อยกเว้น:

[2020-09-29T12: 09: 03.920Z] ข้อผิดพลาด: System.ArgumentException: ประเภทคอมโพเนนต์ต้องใช้ Microsoft.AspNetCore.Components.IComponent ใน Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.OpenComponent (ลำดับ Int32 ประเภท componentType)

เกิดอะไรขึ้นกับการสืบทอดจาก ComponentBase?

ขอบคุณสำหรับความช่วยเหลือของคุณ

เพิ่มเติม:ฉันเรียก Razor-Component ของฉันแบบนี้และException พ่นที่ตัวสร้าง OpenComponent

RenderFragment CreateFragment() => builder =>
{
  builder.OpenComponent(0, typeof(MyRazorComponent));
  builder.CloseComponent();
}

หวังว่านี่จะช่วยได้

คำตอบ

JoeGER94 Sep 30 2020 at 04:32

ก่อนอื่น - ขอบคุณทุกคนที่ช่วยฉันซาบซึ้งจริงๆ!

หลังจากไม่กี่ชั่วโมงหยุดพัก ฉันพบความผิดพลาดของตัวเอง ...

สิ่งที่ฉันกำลังทำ: ฉันได้สร้างบริการที่โหลด List of Type List บริการนี้ได้รับการแทรกใน Razor-Component

รหัสบริการ:

//this returns a listOfRazorComponents
return AppDomain.CurrentDomain.GetAssemblies()
            .Where(x => x.FullName.StartsWith("SampleApplication")).FirstOrDefault()
            .DefinedTypes.Where(x=>x.BaseType is ComponentBase);

ในส่วนประกอบมีดโกนของฉันฉันได้แสดงรายการส่วนประกอบของมีดโกนซึ่งได้รับการซ่อมแซมโดยบริการ

@page "/"
@inject MyService myService


@CurrentFragment

@code{

  private RenderFragment CurrentFragment { get; set; }
  private List<TypeInfo> listOfRazorComponents;
 
  protected override void OnInitialized
  {
     listOfRazorComponents = new List<TypeInfo>(myService.GetRazorComponents());
     CreateFragment(listOfRazorComponents[0]);
  }

  RenderFragment CreateFragment(Type typeToDisplay) => builder =>
  {
     builder.OpenComponent(0, typeToDisplay);
     builder.CloseComponent();
  };
}

ตอนนี้ความผิดพลาดโง่ ๆ ของฉัน ... หลังจากที่ฉันเพิ่ม @inherits ExampleBase ในส่วนประกอบมีดโกนทั้งหมดของฉันส่วนประกอบไม่ได้ถูกสร้างใหม่โดย "MyService" ของฉันเพราะฉันตรวจสอบที่นั่นเพื่อ

x=>x.BaseType is ComponentBase 

สิ่งนี้ทำให้รายการ Razor-Components ว่างเปล่าและเมื่อฉันเรียกCreateFragment(Type typeToDisplay)typeToDisplay เป็นโมฆะ

ฉันไม่เข้าใจจริงๆว่าทำไมbuilder.OpenComponent(0, null)ไม่โยน NullReferenceException นั่นทำให้ฉันสับสน

ความผิดพลาดโง่ ๆ ของตัวเองทำให้ฉันหงุดหงิดมาก ... หวังว่านี่จะป้องกันไม่ให้คนอื่นลืมสิ่งนี้ :)