Find classes implementing a generic class using a Type 'x' as the generic type argument
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I have an interface for defining events with some implementations var opType = typeof(OrderPersisted);//Your choice
var myType = typeof (EventHandlerBase<>).MakeGenericType(opType);
var myExpectedTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.IsSubclassOf(myType))
.ToArray();
|
Defining generic property in abstract class as a type of the implementing class
Tag : java , By : protagonist
Date : March 29 2020, 07:55 AM
will help you Let's say I have a class like: , Sure. Try this. public abstract class Foo<T extends Foo<T>> {
public List<T> container;
protected Foo() {
enforceConstraints();
}
private void enforceConstraints() {
boolean valid = true;
try {
valid =
((ParameterizedType) this.getClass().getGenericSuperclass())
.getActualTypeArguments()[0]
.equals(
this.getClass()
);
} catch (ClassCastException cce) {
valid = false;
}
if (!valid) {
String name = this.getClass().getSimpleName();
throw new IllegalImplementationException(
name + " must be declared as "+ "\"class " + name + " extends Foo<"+name+">\"");
}
}
private static class IllegalImplementationException extends RuntimeException {
IllegalImplementationException(String message) {
super(message);
}
}
}
public class Foo<T> where T : Foo<T> {
public List<T> container;
protected Foo() {
enforceConstraints();
}
private void enforceConstraints() {
if (!this.GetType().Equals(typeof(T))) {
String name = this.GetType().Name;
throw new IllegalImplementationException(
name + " must be declared as " + "\"class " + name + " : Foo<" + name + ">\"");
}
}
}
public class IllegalImplementationException : Exception {
public IllegalImplementationException(String message) : base(message) {}
}
|
Deserializing JSON into generic where collection property name changes based on type
Tag : chash , By : kdietz
Date : March 29 2020, 07:55 AM
seems to work fine Alright, this is working, but it's certainly not the prettiest thing I've ever seen (not totally happy with the intermediate step of converting to a Dictionary). Leaving this question open for now in case somebody knows a better way to do this. The various objects: public class Response {
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
public class Response<T> : Response {
[JsonProperty("data")]
[JsonConverter(typeof(DataConverter))]
public List<T> Data { get; set; }
}
public class DataConverter : JsonConverter {
public override bool CanConvert(Type objectType) {
return typeof(List<object>).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
Dictionary<string, object> data = (Dictionary<string, object>)serializer.Deserialize(reader, typeof(Dictionary<string, object>));
foreach (KeyValuePair<string, object> kvp in data) {
if (kvp.Key != "total_count") {
return ((JToken)kvp.Value).ToObject(objectType);
}
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new NotImplementedException();
}
}
public Response<Customer> GetCustomers() {
string response = SendRequest("/api/v1/customers");
Response<Customer> aresponse = JsonConvert.DeserializeObject<Response<Customer>>(response);
}
|
Infer generic type in property (like in a function) for proper type checking
Date : March 29 2020, 07:55 AM
I hope this helps . So since this is not possible, a practical approach is to use a setter or a factory that enforces the type constraints. E.g.: type Thing<T, A> = {
a: A,
b: SomeTypeDependingoOn<A>
};
class Factory<T> {
public getThing<A, B extends SomeTypeDependingoOn<A>>(a: A, b: B): Thing<T, A>{
return { a: a, b: b };
}
}
let thing: Thing<string, any>;
thing = new Factory<string>().getThing(...); // type checking
|
typescript: how to return proper type from generic function constrained by lookup type generic returning union
Date : December 22 2020, 06:30 AM
Any of those help One option is to use a mapping interface instead of using a conditional type, makes the return type easier to follow. Also I generally use a separate implementation signature with the generics and an implementation signature that is not generic and returns a union. While this is not 100% type safe it is better than the type assertion version. type Action = 'GREET' | 'ASK'
interface ProperReturn {
'GREET': { hello: 'Guten Tag!' }
'ASK': { time: 'Wie spat is es?' }
}
function getUnion<T extends Action>(action: T): ProperReturn[T]
function getUnion(action: Action): ProperReturn[keyof ProperReturn] {
switch (action) {
case 'GREET':
return { hello: 'Guten Tag!' } as const
case 'ASK':
return { time: 'Wie spat is es?' } as const
default:
throw "WUT";
}
}
|