如何在运行时从另一个类中的泛型方法获取类名?



我正在尝试使用UriBuilder生成我的baseurl。我在我的TestUtil类中创建了一个通用的"GetRequestUrl"。如何使用此方法在运行时获取我的测试类的名称并附加到字符串 serviceAPI

这是我的 TestUtil 类中的 GetRequestUrl 方法

public class TestUtil
{
public string GetRequestUrl(string serviceName)
{
string serviceAPI = this.GetType().BaseType.Name;
var requestUrl = new UriBuilder();
requestUrl.Scheme = "http";
requestUrl.Host = "svc-" + serviceName + "." + 
ConfigurationManager.AppSettings["TestEnvironment"] + "-example.com/api/";
requestUrl.Path = serviceAPI;
Uri uri = requestUrl.Uri;
return uri.ToString();
}
}

这是我的测试类,我希望类名"TestClass"在运行时附加到serviceAPI字符串,但我得到了TestUtil。我已经尝试了以下..

这。GetType((。名字;

这。GetType((。BaseType.Name;

MethodBase.GetCurrentMethod((.DeclaringType.Name;

public class TestClass
{
TestUtil util = new TestUtil();
[Test]
public void Method1()
{
string fullUrl = util.GetRequestUrl("APIServiceName");
}
}

您需要将类作为参数传递给 GetRequestURL 或要追加的字符串。字符串更好,因为它可以防止您将来需要更改代码以采用不同的做法。以您似乎想要的方式执行此操作是使用反射,如果您可以这样做,则应避免这样做:

公共类 TestUtil { public string GetRequestUrl(string testType, string serviceName( { 字符串服务API = 测试类型; var requestUrl = new UriBuilder((; requestUrl.Scheme = "http"; requestUrl.Host = "svc-" + serviceName + "." + 配置管理器.应用设置["测试环境"] + "-example.com/api/"; requestUrl.Path = serviceAPI; Uri uri = requestUrl.Uri; 返回 URI。ToString((; } } 公共类测试类 { TestUtil util = new TestUtil((; [测试] 公共无效方法1(( { 字符串 fullUrl = util。GetRequestUrl(this.GetType((。ToString((, "APIServiceName"(; } }

另一种选择是在构造函数中传递它并将其存储为私有变量,这将数据集中,以便您只传入一次。使用接口比使用类更可取:

使用接口方法:

空接口很好。 然后,TestUtil 将需要一个 ServiceAPI 才能使用它的 构造函数作为保证。 公共接口 IServiceAPI { }  使用系统反射; 公共类 TestUtil { 私人_service; TestUtil 需要一个 ServiceAPI 类。 public TestUtil (IServiceAPI service( { _service = 服务; } 公共字符串 GetRequestUrl(string serviceName( { 字符串服务API = _service。GetType((。名字;获取类名。 var requestUrl = new UriBuilder((; requestUrl.Scheme = "http"; requestUrl.Host = "svc-" + serviceName + "." + 配置管理器.应用设置["测试环境"] + "-example.com/api/"; requestUrl.Path = serviceAPI; Uri uri = requestUrl.Uri; 返回 URI。ToString((; } } 在 TestClass 上实现 IServiceAPI 接口。 公共类 测试类 : IServiceAPI { 在这里使用"this"传递测试类。 TestUtil util = new TestUtil(this(; [测试] 公共无效方法1(( { 字符串 fullUrl = util。GetRequestUrl("APIServiceName"(; } }

最新更新