获取 class 并通过字符串调用它的方法
Get class and call method of it by string
我在 appsettings.json
中有匹配策略的价值,它是字符串
我还有class同名
这是示例
public class FuzzyCompanyNameStrategy : MatchingScoreCalculationStrategy
{
public override int CalculateScore(ScoreInputModel input, SupplierModel supplier) =>
Fuzz.Ratio(input.CompanyName, supplier.SupplierNameNormalized);
}
我在需要获取此 class 和方法的地方编写代码,我有输入参数 - 此 Class 的名称,但它是字符串。
这是这个class
protected async Task<MatchingScoreOutput> FindMatch(string name, string postalCode, string city, string matchingStrategy)
{
try
{
string comparisonName = ComparablePropsHelper.GetComparableCompanyName(name);
string comparisonPostalCode = ComparablePropsHelper.GetComparablePostalCode(postalCode);
string comparisonCity = ComparablePropsHelper.GetComparableCityName(city);
var jobSuppliers = await _dataPipelineDbContext.JobSuppliers.AsNoTracking().ToListAsync();
return new MatchingScoreOutput
{
MatchFound = true,
Confidence = MatchConfidence.HIGH,
Score = ,
};
}
catch (Exception ex)
{
_logger.LogError(ex,
$"{nameof(GenericScoreSupplierComparisonService<TEntity>)}: Exception occurred. Message: {ex.Message}");
throw;
}
在 Score =
中,我需要以某种方式调用来自 matchingStrategy
的策略并调用 CalculateScore
我该怎么做?
一些方法可以做到这一点
使用 System.Reflection
获取定义类型的程序集。
程序集 class 有一个 GetType 方法,它接受一个字符串并将 return 类型。
创建该类型的一个实例,将其转换为 MatchingScoreCalulationStrategy 并调用该方法。
它可以变得非常繁琐。我个人更喜欢使用属性,这样策略的名称就不必是 class 名称。
我在 appsettings.json
中有匹配策略的价值,它是字符串
我还有class同名
这是示例
public class FuzzyCompanyNameStrategy : MatchingScoreCalculationStrategy
{
public override int CalculateScore(ScoreInputModel input, SupplierModel supplier) =>
Fuzz.Ratio(input.CompanyName, supplier.SupplierNameNormalized);
}
我在需要获取此 class 和方法的地方编写代码,我有输入参数 - 此 Class 的名称,但它是字符串。
这是这个class
protected async Task<MatchingScoreOutput> FindMatch(string name, string postalCode, string city, string matchingStrategy)
{
try
{
string comparisonName = ComparablePropsHelper.GetComparableCompanyName(name);
string comparisonPostalCode = ComparablePropsHelper.GetComparablePostalCode(postalCode);
string comparisonCity = ComparablePropsHelper.GetComparableCityName(city);
var jobSuppliers = await _dataPipelineDbContext.JobSuppliers.AsNoTracking().ToListAsync();
return new MatchingScoreOutput
{
MatchFound = true,
Confidence = MatchConfidence.HIGH,
Score = ,
};
}
catch (Exception ex)
{
_logger.LogError(ex,
$"{nameof(GenericScoreSupplierComparisonService<TEntity>)}: Exception occurred. Message: {ex.Message}");
throw;
}
在 Score =
中,我需要以某种方式调用来自 matchingStrategy
的策略并调用 CalculateScore
我该怎么做?
一些方法可以做到这一点 使用 System.Reflection 获取定义类型的程序集。 程序集 class 有一个 GetType 方法,它接受一个字符串并将 return 类型。 创建该类型的一个实例,将其转换为 MatchingScoreCalulationStrategy 并调用该方法。 它可以变得非常繁琐。我个人更喜欢使用属性,这样策略的名称就不必是 class 名称。