C#函数<>;委托属性设置器问题

本文关键字:属性 设置 问题 函数 lt gt | 更新日期: 2023-09-27 17:59:49

我正试图使用如下委托返回IDocumentTemplateProvider类型的对象:

public static class DocumentTemplateProvider
{
    private static Func<IDocumentTemplateProvider> _docTemplateProvider;
    public static void SetdocTemplateProvider(Func<IDocumentTemplateProvider> docTemplateProvider)
    {
        _docTemplateProvider = docTemplateProvider;
    }
    public static void SetDocTemplateProvider<T>() where T : IDocumentTemplateProvider, new()
    {
        _docTemplateProvider = () => new T();
    }
    public static IDocumentTemplateProvider TemplateProvider
    {
        get { return _docTemplateProvider(); }
    }
}

然而,当我用调用它时

private static readonly IDocumentTemplateProvider _template = DocumentTemplateProvider.TemplateProvider;

_template始终为空。我对C#Func<gt;这样我就看不出我做错了什么。有人能给我指正确的方向吗?

感谢

更新:为了消除蚂蚁的困惑,我添加了完整的代码,其中_template被初始化并按原样使用:

 public class DocumentModule : IHttpModule
{
        private static readonly IDocumentTemplateProvider _template = DocumentTemplateProvider.TemplateProvider;
        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnBeginRequest;
            context.EndRequest += OnEndRequest;
        }      
        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnBeginRequest;
            context.EndRequest += OnEndRequest;
        }
        private void OnBeginRequest(object sender, EventArgs eventArgs)
        {
            _template.SetProvider();
        }
        private void OnEndRequest(object sender, EventArgs e)
        {
            _template.Finalize();
        }        
        public void Dispose()
        {
        }
}

C#函数<>;委托属性设置器问题

它为null,因为它从未被设置过。您有两个设置_docTemplateProvider变量的Void方法,因此需要首先调用它们,如下面的示例代码

class Program
{
    private static void Main()
    {
        DocumentTemplateProvider.SetDocTemplateProvider<Test>();
        //OR
        DocumentTemplateProvider.SetdocTemplateProvider(() => new Test());
        IDocumentTemplateProvider _template = DocumentTemplateProvider.TemplateProvider;
        Console.ReadLine();
    }
    public static class DocumentTemplateProvider
    {
        private static Func<IDocumentTemplateProvider> _docTemplateProvider;
        public static void SetdocTemplateProvider(Func<IDocumentTemplateProvider> docTemplateProvider)
        {
            _docTemplateProvider = docTemplateProvider;
        }
        public static void SetDocTemplateProvider<T>() where T : IDocumentTemplateProvider, new()
        {
            _docTemplateProvider = () => new T();
        }
        public static IDocumentTemplateProvider TemplateProvider
        {
            get { return _docTemplateProvider(); }
        }
    }
}
internal interface IDocumentTemplateProvider
{
}
public class Test : IDocumentTemplateProvider
{
}