[英]Accessing type <T> passed in from class (public class TheClass<T>) in the method
例如我有一個課:
public class GenericController<T> : ApiController where T : BaseContext
{
public string Get(int id)
{
try
{
var obj = dataRepository.Get<T>(id);
responseMessage.SetGetSuccess(obj);
}
catch (Exception e)
{
responseMessage.SetGetUnsuccess(e);
}
return responseMessage.ToJsonString();
}
}
這可能嗎? 方法中無法識別T
錯誤消息是這樣的:
Error 16 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'AppCore.NHibernateBases.DataRepositories.Interfaces.IDataRepository.Get<T>(int)' C:\Users\SeanPC\Google Drive\SideProject\DataAPI\DataAPI\Controllers\GenericController.cs 44 27 DataAPI
T
在您的方法中被識別。 問題不同。 它不適合您要調用的Get
方法的通用約束集。
“ T”必須是具有公共無參數構造函數的非抽象類型,以便在通用類型或方法“
AppCore.NHibernateBases.DataRepositories.Interfaces.IDataRepository.Get<T>(int)
”AppCore.NHibernateBases.DataRepositories.Interfaces.IDataRepository.Get<T>(int)
其用作參數“ T”
為了使它起作用,您必須在類上添加相同的約束:
public class GenericController<T> : ApiController where T : BaseContext, new()
錯誤說明了一切,您缺少約束。 Get<T>
方法需要的類型not abstract
並且具有無參數的構造函數。
為了能夠將T
類型傳遞給Get
,您必須更改約束:
public class GenericController<T> : ApiController where T : BaseContext, new()
{
public string Get(int id)
{
try
{
var obj = dataRepository.Get<T>(id);
responseMessage.SetGetSuccess(obj);
}
catch (Exception e)
{
responseMessage.SetGetUnsuccess(e);
}
return responseMessage.ToJsonString();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.