我有以下C代码示例:
int f(const int farg[const 5])
{
}
Run Code Online (Sandbox Code Playgroud)
数组大小的附加const有什么作用?当我省略const时有什么区别?
我有一个协议我的swift代码库我有协议与相关的类型和两个方法.这两种方法都为协议的相关类型定义了不同的通用约束.我想使结构符合协议,但有两种不同的关联类型.
protocol Convertable {
associatedtype TargetType
func convert() -> TargetType
}
func show<T : Convertable where T.TargetType == String>(toShow : T) {
print(toShow.convert())
}
func add<T : Convertable where T.TargetType == Int>(a : T, b : T) -> Int {
return a.convert() + b.convert()
}
struct MyData {
var data : Int
}
Run Code Online (Sandbox Code Playgroud)
作为扩展我使该结构符合的协议,其中TargetType将String以便将它传递给显示方法:
extension MyData : Convertable {
func convert() -> String { return String(self.data) }
}
Run Code Online (Sandbox Code Playgroud)
到目前为止一切都按预期工作.但是现在我也希望Convertable在TargetType绑定到Int 时使结构符合协议.哪个似乎不可能?
我尝试的第一件事是将convert方法的第二个定义添加到扩展名:
extension …Run Code Online (Sandbox Code Playgroud) 将通用类转换为它正在实现的接口时遇到问题.
我的代码是这样的:
interface foo
{
void foobar();
}
class bar: foo
{
public void foobar()
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的工厂通过界面创建我的类的实例,主要是一个简单的微内核(服务定位器).我会在这里简化它.通常它会从配置中查找实现类,而工厂将类型视为T,但这与我遇到的问题无关.
public static class Factory
{
public static Lazy<foo> CreateLazyInstance()
{
Lazy<foo> instance;
Type type = typeof(bar);
Type lazyType = typeof(Lazy<>);
Type toContruct = lazyType.MakeGenericType(type);
instance = (Lazy<foo>)Activator.CreateInstance(toContruct);
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
如果失败的话:
instance = (Lazy<foo>)Activator.CreateInstance(toContruct);
Run Code Online (Sandbox Code Playgroud)
并声明InvalidCastException无法将类型强制转换Lazy<bar>为Lazy<foo>.
有没有办法告诉CLR这个演员会工作还是解决这个问题?