我在C#中有两个类。第一堂课看起来像这样
public class AppConfig
{
public static EmailConfig EmailSetting { get; set; }
}
另一堂课看起来像这样
public class EmailConfig
{
public static string SmtpSectionPath = "MailSettings";
}
现在我想要像这样访问EmailCOnfig字段:
AppConfig.EmailSetting.SmtpSectionPath
但是我无法获得 SmtpSectionPath 。
如何访问所需的功能?
我刚刚更新了我的代码:
public class AppConfig
{
public static EmailConfig EmailSetting { get { return new EmailConfig(); } }
}
public class EmailConfig
{
public string SmtpSectionPath = "MailSettings";
}
这是正确的方法吗?
答案 0 :(得分:1)
只需使用EmailConfig.SmtpSectionPath
。
EmailConfig
的静态字段不属于EmailConfig
的任何特定实例。与某些语言不同,C#禁止将它们视为实例字段。
答案 1 :(得分:0)
简短的回答是,你不能。
您正在尝试访问静态属性,就像它是实例属性一样。
如果它真的必须使用静态属性,那么你应该只使用JOIN
答案 2 :(得分:0)
如果你想像这样调用你的字符串属性:
--Create the Tally Table
CREATE TABLE #Tally (I int);
WITH ints AS(
SELECT 0 AS i
UNION ALL
SELECT i + 1
FROM ints
WHERE i + 1 <= 10)
--And in the numbers go!
INSERT INTO #Tally
SELECT i
FROM ints;
GO
--Create the sample table
CREATE TABLE #Sample (ID int IDENTITY(1,1),
MinP int,
MaxP int);
--Sample data
INSERT INTO #Sample (Minp, MaxP)
VALUES (0,2),
(1,4);
GO
--And the solution
SELECT S.ID,
T.I AS P
FROM #Sample S
JOIN #Tally T ON T.I BETWEEN S.MinP AND S.MaxP
ORDER BY S.ID, T.I;
GO
--Clean up
DROP TABLE #Sample;
DROP TABLE #Tally;
您可以从EmailConfig.SmtpSectionPath
属性中删除静态:
AppConfig.EmailSetting.SmtpSectionPath
因为您在SmtpSectionPath
中将public class EmailConfig
{
public string SmtpSectionPath = "MailSettings";
}
声明为静态。有了这个,EmailConfig
的实例在AppConfig
中是静态的,而EmailConfig
也是如此。但是,如果您创建AppConfig
的新实例,那么您的SmtpSectionPath
不包含“相同”值(它具有相同的引用)
如果您需要EmailConfig
作为静态,那么您应该按照@Tigran的回答。
答案 3 :(得分:0)
我建议如下:
using System;
namespace console
{
public interface ISmptSectionPathProvider
{
string SmtpSectionPath
{
get;
}
}
public class AppConfig : ISmptSectionPathProvider
{
public string SmtpSectionPath
{
get { return Constants.SmtpSectionPath; }
}
}
public class EmailConfig : ISmptSectionPathProvider
{
public string SmtpSectionPath
{
get { return Constants.SmtpSectionPath; }
}
}
public class Constants
{
public static string SmtpSectionPath = "MailSettings";
}
class CommandLineApplication
{
public static void Main(string[] args)
{
ISmptSectionPathProvider provider = new AppConfig();
System.Console.WriteLine(provider.SmtpSectionPath);
provider = new EmailConfig();
System.Console.WriteLine(provider.SmtpSectionPath);
}
}
}
您现在也可以完全删除静态类引用,只使用常量类。对复杂的Object模型使用static
通常会导致非常糟糕的设计决策:您必须绑定到特定的类(多态不能用于其完整扩展)并且可能会遇到内存泄漏。