logo
down
shadow

Proper way a implementing property based on generic type


Proper way a implementing property based on generic type

Content Index :

Proper way a implementing property based on generic type
Tag : chash , By : Olexiy P.
Date : November 25 2020, 07:27 PM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Find classes implementing a generic class using a Type 'x' as the generic type argument


Tag : chash , By : pttr
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


Tag : typescript , By : Gianluca Riccardi
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


Tag : typescript , By : Steve Jones
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";
  }
}
Related Posts Related QUESTIONS :
  • How do I make event callbacks into my win forms thread safe?
  • Genealogy Tree Control
  • WCF Service - Backward compatibility issue
  • Binary patch-generation in C#
  • Tab Escape Character?
  • When do Request.Params and Request.Form differ?
  • The imported project "C:\Microsoft.CSharp.targets" was not found
  • Numeric Data Entry in WPF
  • Print a Winform/visual element
  • C# logic order and compiler behavior
  • When to use an extension method with lambda over LINQtoObjects to filter a collection?
  • How to make a button appear as if it is pressed?
  • C# and Arrow Keys
  • How do you resolve a domain name to an IP address with .NET/C#?
  • Should the folders in a solution match the namespace?
  • How can I evaluate C# code dynamically?
  • CSharpCodeProvider Compilation Performance
  • How can I create Prototype Methods (like JavaScript) in C#.Net?
  • DataTable Loop Performance Comparison
  • CSV string handling
  • What is the best way to do unit testing for ASP.NET 2.0 web pages?
  • High availability
  • What to use for Messaging with C#
  • Accessing a Dictionary.Keys Key through a numeric index
  • ConfigurationManager.AppSettings Performance Concerns
  • What Are Some Good .NET Profilers?
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com