我正在尝试使用委托返回 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 始终为null。我是C#Func&lt;&gt;的新手代表们,所以我不能看到我做错了什么。有人能指出我正确的方向吗?
由于
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()
{
}
}
答案 0 :(得分:1)
它为null,因为它从未设置过。你有两个Void方法设置_docTemplateProvider变量,所以你需要先调用它们,就像下面的示例代码一样
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
{
}