GetField() return null 无故

GetField() return null without reason

我的 GetField 或 GetProprety 函数 returns 为空,我不明白为什么 所以这是一个小代码returns这个问题

private void Application_WindowSelectionChange(MSProject.Window Window, MSProject.Selection sel, object selType)
{
    MSProject.Task task;

    string FieldName = Application.ActiveSelection.FieldNameList[1];
    if (sel.Tasks != null)
    {
        task = sel.Tasks[1];
        var typeValue = task.GetType();
        var typeProp = typeValue.GetField(FieldName);
        var typeGetValue = typeProp.GetValue(task);
    }
}

所以 task 永远不会为空,因为它是我的 if.
的条件 typeValue 得到一个值 {Name = "__ComObject" FullName = "System.__ComObject"}, 但是我的 typePropTypeGetvaluenull

COM 对象的反射与 .NET 不同类。 由于我没有安装 MS Access 我无法证明以下代码。

string FieldName = Application.ActiveSelection.FieldNameList[1];
if (sel.Tasks != null)
{
    task = sel.Tasks[1];
    long projectField = FieldNameToFieldConstant(FieldName, pjProject);
    string value = task.GetField(projectField);
}

来源: https://msdn.microsoft.com/en-Us/VBA/Project-VBA/articles/task-getfield-method-project https://msdn.microsoft.com/en-Us/VBA/Project-VBA/articles/pjfield-enumeration-project https://msdn.microsoft.com/en-Us/VBA/Project-VBA/articles/application-fieldnametofieldconstant-method-project

my GetField or GetProprety function returns null

这是因为GetField方法需要很长时间(msdn reference), but you are feeding it a string. Instead of using the FieldNameList property, which returns the name of the field, use FieldIDList其中returns字段ID.

注意:使用 ActiveCell.Text 属性 获取选择中第一个任务的第一个字段的值。