基本上正如标题所说:
[DataContract(Name = "{0}Item")] //This will format properly
public class GenericItem<T>
{
[DataMember(Name = "The{0}")] //This will NOT format properly
public T TheItem { get; set; }
}
[CollectionDataContract(Name = "{0}Items")] //This will format properly
public SpecialCollection<T> : Collection<T> { }
[ServiceContract(Name = "{0}Service")] //This will NOT format properly
public interface IGenericService<T>
{
[OperationContract(Name = "Get{0}")] //This will NOT format properly
GenericItem<T> Get<T>();
}
所以,你有它......什么有效,什么无效......但问题是......为什么?显然,.NET 能够在使用DataContract
andCollectionDataContract
并声明类型时创建一个具体类型并格式化名称(即GenericItem<Foo>
或SpecialCollection<Foo>
. 那么为什么不DataMember
也能够格式化呢?
我可以按照上面留下的方式(ServiceContract/OperationContract
排序)来理解,但我不明白的是,当你给它一个具体的类型时,操作仍然无法正常工作:
[ServiceContract(Name = "FooService")]
public interface FooService : IGenericService<Foo> { }
public interface IGenericService<T>
{
[OperationContract(Name = "Get{0}")] //This will NOT format properly
T Get<T>();
}
再次,为什么?显然,我在这里声明了一个具体的 Foo 类型,这意味着 IGenericService 是一个 IGenericService<Foo> 所以不应该格式化 OperationContract 名称,因为它知道类型吗?
更新:
我只记得为什么我对无法使用通用格式的 ServiceContract 感到不安......当我实现服务时,我给它一个具体的类型......
//See! I gave it a concrete type to go by!
[ServiceBehavior(...)]
public class MyService : IGenericService<Foo> { ... }
我为此创建了一个Microsoft Connect请求。如果您希望将此功能用于其他属性,请对其进行投票。http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2327048-enable-generics-for-datamemberattribute-serviceco