Activator.CreateInstance MissingMethodException

2019-07-15 03:17发布

I have a class in a c# dll with the following class

public class RequiredTask : Base.BaseObject
{

    public string Name { get; set; }
    public string Description { get; set; }

    public RequiredTask() 
        : base()
    { }

}

Which inherits from this class

public class BaseObject : IBaseObject, INotifyPropertyChanged
{
    public DateTime? UpdatedOn { get; set; }
    public string UpdatedBy
    public DateTime? CreatedOn
    public string CreatedBy 

    public BaseObject() { }

}

Then the UI, is a VB.Net Winform, this form is going to be a base form and is generic so it can work with all the types from the c# library, and it has a new button that needs to instanciate the new type of whatever T is and pass it to a form which will be used to edit T.

this is the form code

Public Class Search(Of T As Library.Base.BaseObject)

        Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
            If MyBase.OpenFormName <> "" Then App.mfrmMDI.OpenForm(MyBase.OpenFormName, DirectCast(Activator.CreateInstance(GetType(T), New Object()), T))
        End Sub

End Class

But I get this error Constructor on type 'Library.Production.RequiredTask' not found. when it reaches

DirectCast(Activator.CreateInstance(GetType(T), New Object()), T)

1条回答
祖国的老花朵
2楼-- · 2019-07-15 03:32

You're getting the exception because there is no matching constructor on the type that takes a single parameter of type object.

Change the call to:

DirectCast(Activator.CreateInstance(GetType(T)), T)

This should automatically call the default constructor, which is the one you have defined.

查看更多
登录 后发表回答