简体   繁体   English

如何获取类的类型并在泛型函数中使用它?

[英]How to get type of class and use it in generic functions?

I built a function to create forms for me based on the model I give it. 我建立了一个函数,可以根据我提供的模型为我创建表单。

using MyProject.Models;
...
public partial class CRUDPage : ContentPage
{
    public CRUDPage()
    {
        InitializeComponent();
        Teacher teacher = new Teacher
        {
            id = 1,
            name = "John Smith",
            DOB = new DateTime(1995, 9, 12),
            place = "Hebron",
            salary = 20.5
        };
        //set the content of the page >>> PCL, Xamarin.forms
        Content = new FormGenerator<Teacher>().GenerateForm(teacher);
    }
}

I'm trying to make the code more dynamic by allowing to create forms using any type of models but with no luck. 我试图通过允许使用任何类型的模型来创建表单,但没有运气,从而使代码更具动态性。 the code should be something like this. 代码应该是这样的。

public partial class CRUDPage : ContentPage
{
    public CRUDPage(object entity)
    {
        InitializeComponent();
        Content = new FormGenerator<typeof(entity) >().GenerateForm(entity);
    }
}

But the above code doesn't work; 但是上面的代码不起作用; looks like Type is not the same as the Class itself. 看起来TypeClass本身不同。

How can I get the "class type" of an object to use it as a generic type in the function? 如何获得对象的“类类型”以将其用作函数中的泛型类型?

Looking at your image of FormGenerator , does mform need to be T ? 看着你的形象FormGenerator ,并mform需要被T Would your code still work if it was object ? 如果是object您的代码是否仍然可以工作? If so you can get rid of the generics and solve the problem. 如果是这样,您可以摆脱泛型并解决问题。

You'll have to use MakeGenericType to create an instance where the type is only known at runtime. 您必须使用MakeGenericType创建一个实例,其中该类型仅在运行时才知道。

public CRUDPage(object entity)
{
    InitializeComponent();
    var type = typeof(FormGenerator<>).MakeGenericType(new [] { typeof(entity) });
    var instance = Activator.CreateInstance(type);
    Content = instance.GetType().GetMethod("GenerateForm").Invoke(instance, new[] { entity });
}

Note that this is much slower than using real generics. 请注意,这比使用真正的泛型要慢得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM