有沒有辦法強制傳遞給屬性的類型參數實現特定的接口?強制類型的屬性參數
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
{
}
不依據此http://msdn.microsoft.com/en-us/library/ms173129(v=VS.100).aspx – 2011-05-27 19:34:07
@鄧肯 - 你是對的!我會修改我的答案... – 2011-05-27 19:35:49
你是對的,事實上,它不會編譯一個非常具體的錯誤!我向VS投擲了一些東西,但沒有智能錯誤,所以我錯誤地認爲它是有效的。多麼奇怪。 – 2011-05-27 19:35:51