我运行 C# 代码来比较 CRM 中的前图像和后图像以确定字段是否更改(长话短说:我无法控制的外部进程每次都更新记录中的每个字段,即使字段没有' t改变了)。我想使用 CRM GetAttributeValue(attributeName) 来执行此操作,但我想在我可能不知道字段名称时动态执行此操作。因此,例如,我想这样做:
// pretend the value of firstname is not hard-coded but submitted on a form
// (not really on a form, but just know it's not hard-coded like it is below.)
string fieldToCheck = "firstname";
if (preImage.GetAttributeValue<T>(fieldToCheck) != postImage.GetAttributeValue<T>(fieldToCheck))
{
// do something here. I've tried something like the below, but it doesn't work with error "t is a variable but used like a type".
Type t = preImage.Attributes[fieldToCheck].GetType();
var val = preImage.GetAttributeValue<t>(fieldToCheck);
}
我遇到的问题是 <T>
可能会有所不同,具体取决于 fieldToCheck
的值.在名字的情况下,它将是 <string>
, 在 new_DateOpened 的情况下它将是 <DateTime>
等等。我一定是脑子痉挛了,因为我应该能够弄清楚如何动态获取 T 的值,但我做不到。
最佳答案
泛型类型参数 T
不等于类型 Type
的实例。您可以使用 typeof(T)
从类型参数 T -> Type
开始,但从 Type -> T
开始并不容易。通常在编译时必须知道类型 T。
你显然可以通过这里的反射来做到这一点(How do I use reflection to call a generic method?):
MethodInfo method = typeof(Entity).GetMethod("GetAttributeValue");
MethodInfo generic = method.MakeGenericMethod(t);
generic.Invoke(preImage, fieldToCheck); // and postImage
关于c# - 在 CRM Online 中动态使用 GetAttributeValue<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832104/