logo
down
shadow

Base API Controller with Generics


Base API Controller with Generics

By : maher sous
Date : November 22 2020, 01:01 AM
it should still fix some issue Posting my comment as answer.
The issue was the new() is just a constraint for type that used in generic class. It will require that this type should have default constructor. If type doesn't have it, then it will produce compilation error.
code :


Share : facebook icon twitter icon
Unit test AngularJS controller that inherits from a base controller via $controller

Unit test AngularJS controller that inherits from a base controller via $controller


By : mattie
Date : March 29 2020, 07:55 AM
this one helps. So it looks like $controller doesn't search for controllers by name in the $provide.value() namespace. Instead you have to use the $controllerProvider.register() method, which is only accessible from the module.config() block. Fortunately it looks like there's a hook we can use to get access to $controllerProvider on the module under test.
The updated test code looks like:
code :
describe("ChildCtrl", function () {
    var BaseCtrl;

    beforeEach(module('my-module', function ($controllerProvider) {
        BaseCtrl = jasmine.createSpy();
        BaseCtrl.$inject = ['$scope', 'frobnicate'];

        $controllerProvider.register('BaseCtrl', BaseCtrl);
    }));

    beforeEach(inject(function ($controller, $rootScope) {
        $controller('ChildCtrl', { $scope: $rootScope.$new() });
    }));

    it("inherits from BaseCtrl", inject(function ($controller, $rootScope) {
        expect(BaseCtrl).toHaveBeenCalled();
    }));

    it("passes frobnicate() function to BaseCtrl that returns 123", function () {
        var args = BaseCtrl.calls.argsFor(0);
        var frobnicate = args[1];

        expect(frobnicate()).toEqual(123);
    });
});
Generics and Inheritance: Using generics with a base-class and its sub-classes

Generics and Inheritance: Using generics with a base-class and its sub-classes


By : bslater
Date : March 29 2020, 07:55 AM
it fixes the issue To me it seems that although you need to keep track of the types, all you really need is a record of the parents' type (and their parents) for each item. Rather than using the type itself in a programming sense why not just use a string label and create a list in the base class for the hierarchy of valid types for the item. That way you can have complex connections and organization and only need to compare a single string to a list to see if it's valid.
code :
using UnityEngine;
using System.Collections.Generic;

public class Item {

  public List<string> validInvTypes = new List<string>();

  //...
}

public class Gem : Item {

  //...
}

public class Ruby : Gem {

  public Ruby()
  {
    validInvTypes.Add("Ruby");
    validInvTypes.Add("Gem");
    validInvTypes.Add("Item");
  }

  //...
}

public abstract class SlotHandler<ItemType> : MonoBehaviour, IDropHandler where ItemType : Item {

  //...

  public void OnDrop(PointerEventData eventData)
  {
    //...

    //string currentInvSlot
    //Item droppedItem

    if (droppedItem.validInvTypes.Contains(currentInvSlot))
      // Swap the items...
  }
}
WPF - A dialog having a base class other than Window, where that base class implements generics

WPF - A dialog having a base class other than Window, where that base class implements generics


By : ckb
Date : March 29 2020, 07:55 AM
I hope this helps you . Yes, you should use the x:TypeArguments directive in the XAML markup.
code :
namespace WpfApp1
{
    public class BaseWindow<T> : Window { }

    public class SomeConcreteClass { }
}
public partial class Window1 : BaseWindow<SomeConcreteClass>
{
    public Window1()
    {
        InitializeComponent();
    }
}
<local:BaseWindow x:Class="WpfApp1.Window1"
        x:TypeArguments="local:SomeConcreteClass"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="Window1" Height="300" Width="300">
    <Grid>

    </Grid>
</local:BaseWindow>
Using Generics in Base Classes in C#: How to ensure methods in the base class return the derived class's type?

Using Generics in Base Classes in C#: How to ensure methods in the base class return the derived class's type?


By : Neethu
Date : March 29 2020, 07:55 AM
With these it helps Short answer: when you need to operate derived classes from base, it can be done with implementing Curiously Recurring Template Pattern, which originally comes from C++, but can be applied to C# as well.
Long answer: In your case, base Measurement class should have one additional generic parameter, which is derived class type. The only limitation there is that you cannot create derived instances with new in base classes if derived classes has constructor with parameters. In example below I use MemberwiseClone which might solve the problem.
code :
public class Measurement<TUnit, TMeasurement>
    where TUnit : struct
    where TMeasurement: Measurement<TUnit, TMeasurement>
{
    private readonly double _value;
    protected Measurement(double value, TUnit unit)
    {
        _value = value;
        Unit = unit;
    }
    protected double Value { get; set; }
    public TUnit Unit { get; protected set; }

    // Conversion Methods - these will get overridden in the derived classes.
    protected virtual double GetValueAs(TUnit unit) => throw new NotImplementedException();

    // Operator overloads
    public static TMeasurement operator +(Measurement<TUnit, TMeasurement> left, Measurement<TUnit, TMeasurement> right)
    {
        //we cannot create new instance of derived class, TMeasurement, which is limitation of generics in C#, so need some workaround there
        //Some kind of clone might be solution for that
        var leftClone = (TMeasurement)left.MemberwiseClone();  
        var resultValue =  leftClone.Value + right.GetValueAs(left.Unit);
        leftClone.Unit = left.Unit;
        leftClone.Value = resultValue;
        return leftClone;
    }
}

public struct LengthUnit
{

}

public sealed class LengthMeasurement : Measurement<LengthUnit, LengthMeasurement>
{
    private LengthMeasurement(double value, LengthUnit unit): base(value, unit)
    {

    }

    public static LengthMeasurement FromMeters(double meters) => throw new NotImplementedException();
}

class Program
{
    static void Main(string[] args)
    {
        var length1 = LengthMeasurement.FromMeters(5);
        var length2 = LengthMeasurement.FromMeters(10);
        LengthMeasurement length3 = length1 + length2;
    }
}
Generics - can not return Base for T with T extends Base

Generics - can not return Base for T with T extends Base


By : Gravot3
Date : March 29 2020, 07:55 AM
wish of those help Explanation
By introducing a generic parameter T, you are giving the user of your class the possibility to set a type for you.
code :
public class Farm<A extends Animal> {
    public A produce() {
        // ...
    }
}
Farm<Pig> pigFarm = new Farm<>();

Pig pig = produce();
public A produce() {
    return new Animal();
}
Related Posts Related Posts :
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • Using same alias for multiple namespaces
  • how to move mails into separate folders
  • Multithreaded Uploader
  • Memory fragmentation?
  • C# correct exception handling
  • "Could not open macro storage" when accessing using file on another machine
  • How to access other directories of hosted server
  • C# Jagged Array check if value exists/true
  • Why can't I type Clone() properly?
  • exception on accessing dictionary from list
  • Getting the immediate response from server without waiting to 200 message
  • Why am I getting exception Directory Is Not empty?
  • Could not load file or assembly 'CefSharp.dll' or one of its dependencies
  • Sending Email By Using C# in unity3D?
  • Correct usage of await async in webapi
  • Program update code issue
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org