【发布时间】:2015-08-12 06:51:17
【问题描述】:
这是我的问题:
我们制作了一个可移植的类库,其中包含一个 CommonColors 类,其中包含一个颜色列表,我们的所有客户端软件都可以将其用作产品的通用配色方案。在颜色在非可移植类库中定义之前它们可以正常工作,但现在它们无法在 Web 客户端视图中访问。在其他任何地方(Asp.Net 代码隐藏,WPF)它们都可以正常工作。
客户端包括带有剃须刀视图的 Asp.Net Web 客户端、WPF 客户端以及某种移动客户端。
我们在运行时遇到的错误是:“CS1061:'string' 不包含 'ToHtmlColorValue' 的定义,并且找不到接受 'string' 类型的第一个参数的扩展方法 'ToHtmlColorValue'(您是否缺少使用指令还是程序集引用?)”
程序集引用正确,Web 项目中有对可移植类库的引用。它们在视图中的引用方式如下:
@{
string bgcolor = "#" + MySpace.Common.CommonColors.MyTestColor.ToHtmlColorValue();
}
<div id="testdiv" style="background-color:@(bgcolor);">
</div>
这是我的可移植类库项目中的颜色类:
namespace MySpace.Common
{
public static class CommonColors
{
private static string FromRgb(int r, int g, int b)
{
return r.ToString() + "," + g.ToString() + "," + b.ToString();
}
public static string ToHtmlColorValue(this string rgb)
{
string result = "000000";
try
{
string[] parts = rgb.Split(',');
int r = int.Parse(parts[0]);
int g = int.Parse(parts[1]);
int b = int.Parse(parts[2]);
result = r.ToString("x2") + g.ToString("x2") + b.ToString("x2");
}
catch
{
// do nothing
}
return result;
}
public static string MyTestColor = FromRgb(100, 165, 0);
// more colors...
}
}
我想了解究竟是什么导致了这个问题,并将实现修复为更优雅和更好的代码。目前,我们可以在每个使用颜色的视图中添加一行@using MySpace.Common,但这会产生不可靠的代码,需要编码人员知道/记住使用该 using 语句,否则会在运行时出现意外错误。
添加 using 语句使该方法在视图中可见,但在使用相同命名空间路径的视图中引用它则不会。为什么?
【问题讨论】:
标签: c# asp.net asp.net-mvc razor