i have a base class called Event which is inherited by Generic class type called RequestModel now i have to convert base class object to derived class without knowing type of "T" in request model. Following is the thing that i have done. Thank you in advance for helping.
public class RequestModel<T>:Event
{
public Guid Id { get; set; }
public T Model{ get; set; }
public string IpAddress { get; set; }
public string EntityType => typeof(T).ToString();
public override Type RequestEntityType { get { return typeof(T); }}
public UserDataViewModel UserData { get; set; }
public string Url { get; set; }
public DateTime LogDate { get; set; }
public RequestModel()
{
Id = Guid.NewGuid();
}
}
public abstract class Event
{
public abstract Type RequestEntityType { get; }
}
i have collection of event class where i add RequestModel
public List<Event> AllEvents = new List<Event>();
Here is the function where i get each event out of collection
public void RunLogEvent()
{
foreach (var eventItem in AllEvents)
{
try
{
var mappedData = MapData(eventItem);
_creditCardLogService.Add(mappedData);
}
catch (Exception ex)
{
continue;
}
}
_unitOfWork.Commit();
}
Here is the MapData function where is type conversion to which i actually need to convert event object to RequestModel object
private CreditCardLog MapData(Event request)
{
var b = Activator.CreateInstance(request.RequestEntityType);
var a = CastToMyType(b, request);
var serializer = new JavaScriptSerializer();
var returnData = new CreditCardLog()
{
AppraisalFormID = ApparisalId,
CreatedBy =null ,
CreatedDate = a.LogDate,
LogID = a.Id,
Data = serializer.Serialize(a.Model)
};
//return returnData;
return returnData;
}
public RequestModel<T> CastToMyType<T>(T NeededType, object givenObject) where T : class
{
var newObject = givenObject as RequestModel<T>;
return newObject;
}
last function CastToMyType is the casting function which i desperiately need to cast object to RequestModel type which i am right now unable to do so please if anyone could help it will be great. thank you.
Aucun commentaire:
Enregistrer un commentaire