[英]Casting to correct type after using Activator.CreateInstance
在使用只返回對象類型的Activator.CreateInstance(...)之后,我遇到了轉換為正確類型的問題。 所以我的代碼如下。 我有一個空接口將對象定義為命令..
/// <summary>
/// Defines the expected members for a Command object
/// </summary>
public interface ICommand { }
我有一個實現該接口的命令
/// <summary>
/// Contains command data for adding a company
/// </summary>
public class CompanyAddCommand : ICommand
{
#region Properties
public bool IsActive { get; protected set; }
public string CompanyName { get; protected set; }
public DateTime RecordCreatedDateTime { get; protected set; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CompanyAddCommand"/> class.
/// </summary>
/// <param name="isActive">if set to <c>true</c> [is active].</param>
/// <param name="companyName">Name of the company.</param>
/// <param name="recordCreatedDateTime">The record created date time.</param>
public CompanyAddCommand(bool isActive,
string companyName, DateTime recordCreatedDateTime)
{
IsActive = isActive;
CompanyName = companyName;
RecordCreatedDateTime = recordCreatedDateTime;
}
#endregion
}
我有一個命令驗證器接口,它具有單個方法Validate()並且具有一個類型參數,該參數是必須是類並實現ICommand接口的對象。
public interface IValidationHandler<in TCommand>
where TCommand : class, ICommand
{
/// <summary>
/// Validates the specified command.
/// </summary>
/// <param name="command">The command.</param>
void Validate(TCommand command);
}
我有一個實現IValidationHandler的命令驗證器類
public class CompanyAddValidator : ValidatorBase, IValidationHandler<CompanyAddCommand>
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CompanyAddValidator"/> class.
/// </summary>
public CompanyAddValidator(IUnitOfWork unitOfWork)
: base(unitOfWork)
{ }
#endregion
#region IValidationHandler<CompanyAddCommand> Members
/// <summary>
/// Validates the specified command.
/// </summary>
/// <param name="command">The command.</param>
public void Validate(
CompanyAddCommand command)
{
ValidateCompanyEntity(command);
ValidationUniqueCompanyName(command);
}
#endregion
/// <summary>
/// Validates the company entity.
/// </summary>
/// <param name="command">The command.</param>
private void ValidateCompanyEntity(CompanyAddCommand command)
{
// do some work
}
/// <summary>
/// Validations the name of the unique company.
/// </summary>
/// <param name="command">The command.</param>
private void ValidationUniqueCompanyName(CompanyAddCommand command)
{
// do some work;
}
}
我有一個命令總線,在構造中掃描程序集以查找處理程序類型的所有類,並將這些類型作為命令處理程序或驗證處理程序注冊到兩個字典之一,其中鍵是命令類型,值是處理程序類型。
public class CommandBus : ICommandBus
{
#region Fields
private Dictionary<Type, Type> _commandHandlerTypes;
private Dictionary<Type, Type> _validationHandlerTypes;
private readonly IUnitOfWork _unitOfWork;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CommandBus"/> class.
/// </summary>
public CommandBus(IUnitOfWork unitOfWork)
{
// Validate arguments
if (unitOfWork == null) throw new ArgumentNullException("unitOfWork");
// Cache the UOW
_unitOfWork = unitOfWork;
RegisterAllHandlerTypes();
}
#endregion
#region ICommandBus Members
/// <summary>
/// Submits the specified command.
/// </summary>
/// <typeparam name="TCommand">The type of the command.</typeparam>
/// <param name="command">The command.</param>
/// <returns></returns>
public ICommandResult Submit<TCommand>(TCommand command)
where TCommand : class, ICommand
{
Validate(command);
return SubmitInternal(command);
}
#endregion
#region Methods : private
/// <summary>
/// Gets the command handler types.
/// </summary>
/// <returns></returns>
private static Dictionary<Type, Type> GetCommandHandlerTypesFromAssembly()
{
// Create a function that will return true if the type is of type ICommandHandler
Func<Type, bool> isCommandHandler = t => t.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler<>));
// Use this function to register the command handlers in this assembly
Assembly assembly = Assembly.GetCallingAssembly();
return GetSpecificHandlerTypesFromAssembly(assembly, isCommandHandler);
}
/// <summary>
/// Registers all of the handler types.
/// </summary>
private void RegisterAllHandlerTypes()
{
_commandHandlerTypes = GetCommandHandlerTypesFromAssembly();
_validationHandlerTypes = GetValidationHandlerTypesFromAssembly();
}
/// <summary>
/// Gets the specific handler types using the specified function to determine correct types.
/// </summary>
/// <param name="assembly">The assembly to get hansdlers from</param>
/// <param name="isCorrectTypeCallback">A function that returns true if the Type is correct.</param>
/// <returns></returns>
private static Dictionary<Type, Type> GetSpecificHandlerTypesFromAssembly(
Assembly assembly,
Func<Type, bool> isCorrectTypeCallback)
{
Func<Type, IEnumerable<Tuple<Type, Type>>> collect = t => t.GetInterfaces()
.Select(i => Tuple.Create(i.GetGenericArguments()[0], t));
return assembly
.GetTypes()
.Where(t => !t.IsAbstract && !t.IsGenericType)
.Where(isCorrectTypeCallback)
.SelectMany(collect)
.ToDictionary(x => x.Item1, x => x.Item2);
}
/// <summary>
/// Gets the validation handlers.
/// </summary>
/// <returns></returns>
private static Dictionary<Type, Type> GetValidationHandlerTypesFromAssembly()
{
// Create a function that will return true if the type is of type IValidationHandler
Func<Type, bool> isValidationHandler = t => t.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IValidationHandler<>));
// Use this function to register the validation handlers in this assembly
Assembly assembly = Assembly.GetCallingAssembly();
return GetSpecificHandlerTypesFromAssembly(assembly, isValidationHandler);
}
private ICommandResult SubmitInternal(object command)
{
// do some work
}
private void Validate<TCommand>(TCommand command)
where TCommand : class, ICommand
{
// Get the command type and check if we have a validator for that type
Type commandType = command.GetType();
bool hasValidator = _validationHandlerTypes.ContainsKey(commandType);
// If we don't have a validator dont worry, just break leve the method
if (!hasValidator) return;
// Create and instance of the handler
Type validatorType = _validationHandlerTypes[commandType];
var handler = Activator.CreateInstance(validatorType, _unitOfWork);
Type handlerType = handler.GetType();
var handlerB = handler as IValidationHandler<TCommand>;
var handlerC = handler as IValidationHandler<ICommand>;
//handler.Validate(command); compiler fails as handler is OBJECT
if (handlerB != null) handlerB.Validate(command);
if (handlerC != null) handlerC.Validate(command);
}
#endregion
}
我遇到的問題是在Validate()方法中,雖然我可以創建一個命令驗證器的實例,它顯示(懸停在變量上)它是正確的類型(即CompanyAddValidator的一個實例)我不能調用Validate()方法,因為它是一個對象。 如果我嘗試將此處理程序轉換為IValidationHandler <TCommand>或IValidationHandler <ICommand>(即handlerB和handlerC),那么我可以在接口上調用“Validate()”方法,我得到一個空引用。
我無法獲得允許我需要的泛型級別的正確語法,並且能夠在實例化的CompanyAddValidator對象或我可能擁有的任何其他域實體驗證器上調用Validate()方法。
任何人都可以指出我正確的方向嗎? 我試着按照這些例子但沒有運氣。
你可以這樣做:
dynamic handler = Activator.CreateInstance(validatorType, _unitOfWork);
handler.Validate((dynamic)command);
或者你可以這樣做:
handler.GetType().GetMethod("Validate").Invoke(handler,new object[] {command});
注意:如果您之前沒有閱讀過,我建議您閱讀如何編寫Minimal,Complete和Verifiable示例 。 你給出的代碼是quire不一致的,例如,你試圖調用沒有參數的handler.Validate
,其中方法是用一個參數定義的,你在CommandBus
類上的Submit
方法什么都不返回,而它的簽名需要結果ICommandResult
et cetra,et cetra的類型。 這使得回答您的問題變得更加困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.