我有一个包含多个变量的类,可以通过它们自己的属性访问:
TGame = class(TObject)
strict private
FValue1 : Integer;
FValue2 : Integer;
private
procedure SetValue1(const Value : Integer);
procedure SetValue2(const Value : Integer);
function GetValue1() : Integer;
function GetValue2() : Integer;
public
property Value1 : Integer read GetValue1 write SetValue1;
property Value2 : Integer read GetValue2 write SetValue2;
Run Code Online (Sandbox Code Playgroud)
我想知道,是否有办法对不同的属性使用相同的 Getter 和 Setter,如下所示:
property Value1 : Integer read GetValue write SetValue;
property Value2 : Integer read GetValue write SetValue;
Run Code Online (Sandbox Code Playgroud) 我目前正在开发一个巨大的项目,该项目不断执行查询。我的问题是,我的旧代码总是创建一个新的数据库连接和游标,这极大地降低了速度。所以我认为是时候创建一个新的数据库类了,目前看起来像这样:
class Database(object):
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = object.__new__(cls)
try:
connection = Database._instance.connection = mysql.connector.connect(host="127.0.0.1", user="root", password="", database="db_test")
cursor = Database._instance.cursor = connection.cursor()
except Exception as error:
print("Error: Connection not established {}".format(error))
else:
print("Connection established")
return cls._instance
def __init__(self):
self.connection = self._instance.connection
self.cursor = self._instance.cursor
# Do database stuff here
Run Code Online (Sandbox Code Playgroud)
查询将使用该类,如下所示:
def foo():
with Database() as cursor:
cursor.execute("STATEMENT")
Run Code Online (Sandbox Code Playgroud)
我不确定,无论创建该类的频率如何,这是否仅创建一次连接。也许有人知道如何仅初始化一次连接以及如何在之后的类中使用它,或者可能知道我的解决方案是否正确。我很感谢任何帮助!
我有一个类库,由控制台应用程序使用。ILogger<T>我现在想在我的类库中添加通过构造函数注入。我想出了这样的事情:
public class Class1
{
private readonly ILogger<Class1> _logger;
public Class1(ILogger<Class1> logger)
{
_logger = logger;
}
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何才能交出ILogger<T>。
public class Program
{
public static void Main(string[] args)
{
Class1 clazz = new Class1(?????);
}
}
Run Code Online (Sandbox Code Playgroud)