c# - 如何从一个类获取泛型类型到另一个c#
问题描述
是否可以将泛型类型从一个类传递到另一个类的泛型属性。
例如:
装配记录仪
namespace Logger
{
public class GenericLoger<T>
{
T _genericLog;
LogManager _logManager;
public GenericLoger(string logName)
{
_logManager = new LogManager(logName);
//Assigning the generic type to Log.GenerciLog, this is how I am
expecting or by some other possible way?.
Log.GenerciLog = _genericLog;
}
public static Write(string description)
{
_logManager.write(description);
}
}
public static class Log
{
LogManager _logManager;
static Log()
{
_logManager = new LogManager();
}
public static Write(string description)
{
_logManager.write(description);
}
//The generic type supplied in GenericLoger need to pass here,
//like this or by some other possible way?
public static T GenerciLog { get; internal set; }
//T is unrecognized here as type is available in GenericLoger
//I want to pass here from GenericLoger
}
}
记录器的程序集主调用者
using Logger;
namespace DataProcessor
{
internal class SpecialLogger
{
private static Lazy<GenericLog<SpecialLogger>> _passed;
public static GenericLog<SpecialLogger> Passed
{
get
{
if (_passed == null)
{
_passed = new Lazy<GenericLog<SpecialLogger>>(() => new GenericLog<SpecialLogger>("Passed"), true);
}
return _passed.Value;
}
}
private static Lazy<GenericLog<SpecialLogger>> _failed;
public static GenericLog<SpecialLogger> Failed
{
get
{
if (_failed == null)
{
_failed = new Lazy<GenericLog<SpecialLogger>>(() => new GenericLog<SpecialLogger>("Failed"), true);
}
return _failed.Value;
}
}
}
internal class Processor
{
public void ProcessRate()
{
var trans = dataManager.GetData();
//Will write the log in "Log.txt" file
Log.write(trans.Count + " transaction found");
foreach (var item in trans)
{
try
{
//transaction process code here
//This will write the text in "Passed.txt" file. 'Passed' property I want to access like this
Log.GenerciLog.Passed.Write(item);
}
catch (Exception ex)
{
//This will write the text in "Failed.txt" file. 'Failed' property I want to access like this
Log.GenerciLog.Failed.Write(item);
}
}
}
}
}
解决方案
注意:在 .NET 中,您没有像您这样的用例进行自动类型推断的方法,也没有自动类型替换。
不确定这是否是您要找的
您的方法定义应如下所示
public static T GenerciLog<T> { get; internal set; }
这就是如何称呼它
try
{
//transaction process code here
//This will write the text in "Passed.txt" file. 'Passed' method I want to access like this
Log.GenerciLog<SpecialLogger>.Passed.Write(item);
}
catch (Exception ex)
{
//This will write the text in "Failed.txt" file. 'Failed' method I want to access like this
Log.GenerciLog<SpecialLogger>.Failed.Write(item);
}
推荐阅读
- java - 如何获得修复此错误的 Stacktrace?
- memory - 写入 STM32 内部闪存失败
- c++ - 将函数的输出分配给其他函数 C++ 中的变量
- c# - 1 列的 Linq 不同
- python - 如何解决“ValueError:y 应该是一维数组,得到一个形状为 (3, 5) 的数组。” 对于朴素贝叶斯?
- javascript - 如何从数组中获取关键对象
- django - 我的 s3 图像不会显示在我的 django 网站上
- swiftui - 防止在 UIRepresentableView 中调用 updateUIView()?
- python - python subprocess.Popen 挂在交替的 stdout 和 stderr 写入
- c# - 在 linux azure 应用服务(.net core 3.1)上发布时 SQLite 错误“数据库已锁定”。但我没有使用 SQLite