如何在静态方法中使用class作为参数

时间:2017-11-30 17:43:43

标签: c#

我在处理XML文档的类中有一个静态方法(相关)(不那么相关)。该方法看起来像这样......

public static bool ProcessFormFile(IFormFile formFile, ModelStateDictionary modelState, string fileExtensionToValidate = "docx")
{
    //...some logic & stuff
    MemberInfo property = typeof(UploadTemplateViewModel).GetProperty(formFile.Name.Substring(formFile.Name.IndexOf(".") + 1));

    //... all the rest
}

正如您所看到的,我使用反射从UploadTemplateViewModel获取某些属性。问题是我需要使用SomeOtherViewModel这样的另一个类动态,并在方法中使用它。

我尝试过使用这样的东西......

public static bool ProcessFormFile(IFormFile formFile, ModelStateDictionary modelState, T entity, string fileExtensionToValidate = "docx") where T : class

...但我得到了Constraints are not allowed on non-generic declarations。这是我一直想要了解更多信息的topice,但这是我第一次在真实情况下使用它。

我怎样才能做到这一点?将方法从静态更改为公共或类似的东西?提前谢谢。

该方法有效,我可以通过反射得到属性,我只需要使用typeof(somethingInMethodParameters).GetProperty()

1 个答案:

答案 0 :(得分:5)

你的方法是静态的/公共的/无论什么都没关系,你在这里看到的错误信息是因为你错过了泛型类型说明符。例如:

public static bool ProcessFormFile<T>(...) where T : class
//                                ^^^
//                                Add this

现在您可以在反射代码中使用T

MemberInfo property = typeof(T).GetProperty(...)
相关问题