在运行时将类类型传递给泛型方法

时间:2013-08-12 05:46:30

标签: c# generics reflection runtime

我有一个名为IAuditable的界面,如下所示:

public interface IAuditable
{
    string AuditSummary
    {
        get;
    }
    string AuditDetails
    {
        get;
    } 
}

AuditTrail类中的两个泛型方法如下:

public T GetActualOldValue<T>() where T : IAuditable
    {
        return FromXElement<T>(OldValue);
    }
    public T GetActualNewValue<T>() where T : IAuditable
    {
        return FromXElement<T>(NewValue);
    }

以及我有一个属性可以通过在运行时获取来返回审核摘要,如下所示:

 public string AuditSummary
    {
        get
        {
            if (HasNewValue || HasOldValue)
            {
                string libraryVal = GetLibraryValue();
                Assembly assembly = Assembly.Load(libraryVal);
                foreach (Type type in assembly.GetTypes())
                {
                    if (type.IsClass == true)
                    {
                        if (type.FullName.EndsWith("." + ClassName))
                        {
                            /*Here i want to call GetActualNewValue<foundClass>().AuditSummary
                             * or GetActualOldValue<foundClass>().AuditSummary;
                             */
                        }
                   }
                }
            }
            return "";
        }
    }

如您所知,我们可以在特定的库中找到运行时的课程, 请注意我不想在运行时调用泛型方法,只是想用established调用泛型方法,换句话说,如何将特定类传递给GetActualNewValue&lt; ...&gt;()作为T,

AuditTrail auditTrail = AuditTrail.GetAuditTrail(76);
string summmary = auditTrail.GetActualOldValue<DTClient>().AuditSummary;
string details = auditTrail.GetActualOldValue<DTClient>().AuditDetails;

此代码工作正常,但主要问题是DTClient必须在运行时找到并为GetActualValue定义为T.

谢谢大家。

2 个答案:

答案 0 :(得分:0)

试试这个:

    AuditTrail auditTrail = new AuditTrail();

    var method = auditTrail.GetType().GetMethod("GetActualOldValue");
    var genericMethod = method.MakeGenericMethod(auditTrail.GetType());
    var result = genericMethod.Invoke(auditTrail, null);

答案 1 :(得分:0)

您可以使用静态方法在参数中传递旧对象和更改对象来跟踪更改。

public class
{
    AuditClass.AuditingUserActivity(OldObject,ChangedObject);   
}

class AuditClass
{
    public static void AuditingUserActivity<T>(this T obj1,obj2)
    {
        PropertyInfo[] properties = typeof(T).GetProperties(); //Gets all properties exist in passed objects of both

        foreach (PropertyInfo pi in properties)
        {
            object value1 = typeof(T).GetProperty(pi.Name).GetValue(obj1, null); // gets value for each entity
            object value2 = typeof(T).GetProperty(pi.Name).GetValue(obj2, null);

            if (value1 != null && value2 != null)
            {
                //You can compare and check whether changes made or not
            }
        }
    }             
}