C# 如何编写一个泛型方法来初始化传递给该方法的类型?

C# 如何编写一个泛型方法来初始化传递给该方法的类型?,c#,C#,我有一个类,它通过只包含GET的属性来保存其他类的实例 public class PageInstance : PageInstanceBase { #region Private Members private InquiryPage _inquiryPage; #endregion #region Properties /// <summary> /// Get Inquiry Page. /// </summ

我有一个类,它通过只包含GET的属性来保存其他类的实例

public class PageInstance : PageInstanceBase
{
    #region Private Members

    private InquiryPage _inquiryPage;

    #endregion

    #region Properties

    /// <summary>
    /// Get Inquiry Page.
    /// </summary>
    public InquiryPage InquiryPage
    {
        get
        {
            if (this._inquiryPage == null)
            {
                this._inquiryPage = new InquiryPage();
            }

            return this._inquiryPage;
        }
    }
我被困在这个地方了。非常感谢您的帮助

谢谢


Sham

您可以像指定一样指定一些,但是对于一些抽象,例如
接口
抽象类
。对于示例:

public void Refresh<T>() 
    where T : InquiryPage, new()
{
    _inquiryPage = new T();
}
public class PageInstance<T> : PageInstanceBase, 
    where T : new()           
{
    #region Private Members

    private T _inquiryPage;

    #endregion

    #region Properties

    public T InquiryPage
    {
        get
        {
            if (this._inquiryPage == null)
            {
                this._inquiryPage = new T();
            }

            return this._inquiryPage;
        }
    }

    public void Refresh() 
    {
       this._inquiryPage = new T();
    }
}

在泛型中,在
T
类型中,您在约束中指定了一个空构造函数。

最后,我能够找到如下所述的解决方案。但是,这导致我为所有属性提供private/protected SET属性。约束,页已继承到PageInstanceBase,然后继承到PageInstance

    /// <summary>
    /// Refresh the Page.
    /// </summary>
    /// <typeparam name="T">Page.</typeparam>
    public void Refresh<T>() where T : Page, new()
    {
        Type t = typeof(T);
        PropertyInfo pi = this.GetType().GetProperty(t.Name);
        pi.SetValue(this, new T(), null);
    }
//
///刷新页面。
/// 
///页面。
public void Refresh(),其中T:Page,new()
{
类型t=类型(t);
PropertyInfo pi=this.GetType().GetProperty(t.Name);
设置值(this,new T(),null);
}
现在在调用时,我将调用Refresh()页面,这将this.\u InquiryPage设置为InquiryPage类的新实例

谢谢


Sham

我有多个课程,其中一个是InquiryPage。所有的类都有一个默认构造函数。你对所有这些类都有一些抽象吗。Net Framework不会编译
new T()
,因为它应该是
InquiryPage
。为所有类添加一个接口;或者您也可以将您的
\u查询页面
更改为
T
,并将
T
保留在类作用域上:
public class PageInstance where T:new()
。这是正确的,但需要进行大量的更改。在现有签名上没有干扰的任何其他建议?简单地说,我需要在调用refresh方法时初始化我的页面。喜欢PageInstance_page=new PageInstance()_page.InquiryPage.Refresh();上面需要在InquiryPage中编写一个方法'Refresh()',在这里我可以初始化page并将实例发送到PageInstance中的对象,它是_InquiryPage????难道你不能完成一个完整的泛型类吗?看看我的编辑
    /// <summary>
    /// Refresh the Page.
    /// </summary>
    /// <typeparam name="T">Page.</typeparam>
    public void Refresh<T>() where T : Page, new()
    {
        Type t = typeof(T);
        PropertyInfo pi = this.GetType().GetProperty(t.Name);
        pi.SetValue(this, new T(), null);
    }