繁体   English   中英

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

[英]How to write a generic method which initializes the type passed to that method?

我有一个类,该类通过仅具有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;
        }
    }

}

此类具有10多个属性(10个不同的类实例)。 现在,我想编写一个显式方法,可以根据需要设置值,并且不希望在现有属性中使用SET。

是否可以通过通用方法或任何方式来实现? 喜欢...

public void Refresh<T>() where T : new()
    {
       _inquiryPage = new T();
    }

我被困在这个地方。 非常感谢您的帮助。

谢谢,

假_

您可以像您一样指定一些constraint ,但是要abstract class一些,例如interfaceabstract class 样品:

public void Refresh<T>() 
    where T : InquiryPage, new()
{
    _inquiryPage = new T();
}

在您的情况下,我不知道什么是InquiryPage类型,但是,如果您有一些摘要,则可以在此方法上使用,并保持new()对CLR说,此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类型的约束中指定的内容,在这种情况下为空的构造函数。

最后,我能够找出下面提到的解决方案,但是,这导致我为所有属性提供了私有/受保护的SET属性。 约束,Page已继承到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);
    }

现在,在调用时,我将页面称为Refresh <InquiryPage>(),它将this._inquiryPage设置为InquiryPage类的新实例。

谢谢,

假_

暂无
暂无

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

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