属性参数的强制类型
|
有没有一种方法可以强制将传递给属性的类型参数实现特定的接口?
public interface IExpectedInterface
{
void InterfaceMethod();
}
public class MyCustomAttribute : Attribute
{
public MyCustomAttribute(Type classType)
{
this.ConfirmAssignedClassType();
_classType = classType;
}
public void SomeMethod<T>() where T : IExpectedInterface, new()
{
//var expectedType = Activator.CreateInstance(this._classType) as IExpectedInterface;
var expectedType = Activator.CreateInstance(typeof(T)) as IExpectedInterface;
if (expectedType == null)
{
// Wrong type
throw new ArgumentException(string.Format(\"Wrong type: {0} could not be created or converted to IActionAuthorization\", _classType.ToString()));
}
// Do something with expectedType
expectedType.InterfaceMethod();
}
private void ConfirmAssignedClassType()
{
if (!typeof(IExpectedInterface).IsAssignableFrom(_classType))
{
// Wrong type
// Can we enforce it via language construct
throw new ArgumentException(string.Format(\"Wrong type: {0} must implement IExpectedInterface\", _classType.ToString()));
}
if (this._classType.GetConstructor(Type.EmptyTypes) == null)
{
// Wrong type
// Can we enforce it via language construct
throw new ArgumentException(string.Format(\"Wrong type: {0} must have parameter less constructor\", _classType.ToString()));
}
}
private Type _classType;
}
public class TestClass
{
[MyCustom(typeof(TestClassImplementsExpectedInterface))]
public void TestMethod1()
{
}
[MyCustom(typeof(TestClassDoesntImplementExpectedInterface))]
public void TestMethod2()
{
}
}
public class TestClassImplementsExpectedInterface : IExpectedInterface
{
public void InterfaceMethod()
{
return;
}
}
public class TestClassDoesntImplementExpectedInterface
{
}
没有找到相关结果
已邀请:
4 个回复
缮记箔
当然,另一个答案的翻译使用“ new”很有意义!
甲车劲
刷遍派戳
类型约束表示该类型必须具有公共的无参数构造函数,这意味着您可以执行
。这样就无需使用
。 请注意,正如Duncan Howe指出的那样,泛型类型不能从generic7ѭ继承,所以您不能做
攫怂绵十
)传递对象并将其存储在属性中。然后,如果需要该类型,则显式调用
。