我正在尝试使用委托返回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 代表还很陌生,所以我看不到我在做什么错。有人可以指出我正确的方向吗?谢谢更新:为了消除蚂蚁的困惑,我在_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() { }} (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 它为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{}关于c# - C#Func <>委托(delegate)属性 setter 问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31040419/ (adsbygoogle = window.adsbygoogle || []).push({});