logo
down
shadow

Deep copy object properties (including those with private setter) to another object of the same type


Deep copy object properties (including those with private setter) to another object of the same type

By : Vimto
Date : October 21 2020, 08:10 AM
it helps some times This is because Type.GetProperties only returns properties. What you are searching for is essentially the same code as the CopyPropertiesTo above, but you want to replace GetProperties with GetFields. You also need to specify BindingFlags in the parameters of the method to get private members.
Try this out:
code :
public static void CopyFieldsTo<T, TU>(this T source, TU dest)
{
    var sourceFields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList();
    var destFields = typeof(TU).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList();
    foreach (var sourceField in sourceFields)
    {
        if (destFields.Any(x => x.Name == sourceField.Name))
        {
            var f = destFields.First(x => x.Name == sourceField.Name);
            f.SetValue(dest, sourceField.GetValue(source));
        }
    }
}


Share : facebook icon twitter icon
Private-setter properties in C# 3.0 object initialization

Private-setter properties in C# 3.0 object initialization


By : Jacob S.
Date : March 29 2020, 07:55 AM
this will help Private set on myName means you can only initialize (set) it from something that is a member of MyClass. For example:
code :
        public class MyClass {
        public string myName { get; private set; }
        public string myId { get; set; }

        public static MyClass GetSampleObject() {
            MyClass mc = new MyClass
            {
                myName = "Whatever",
                myId = "1234"
            };
            return mc;
        }
    }
How can I deep copy an object of one object type to another object type that share an inheritance structure

How can I deep copy an object of one object type to another object type that share an inheritance structure


By : Mindshare
Date : March 29 2020, 07:55 AM
Does that help This is a complete tool for copying properties between objects, take a look:
https://github.com/AutoMapper/AutoMapper/wiki
Create a read-only/immutable copy of any object (including deep properties)

Create a read-only/immutable copy of any object (including deep properties)


By : Andrew Mcfarlane
Date : March 29 2020, 07:55 AM
I wish did fix the issue. This is the solution I came up with after some thought. Works well for my needs so I thought I'd share it QnA style. Do suggest any improvements/issues if you you find them.
code :
/**
 * Make the the specified object (deeply) immutable or "read-only", so that none of its
 * properties (or sub-properties) can be modified. The converted object is returned.
 * @param {object} obj Input object
 */
makeImmutable: function makeImmutable (obj) {
    if ((typeof obj === "object" && obj !== null) ||
        (Array.isArray? Array.isArray(obj): obj instanceof Array) ||
        (typeof obj === "function")) {

        Object.freeze(obj);

        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                makeImmutable(obj[key]);
            }
        }
    }
    return obj;
}
Javascript - Deep copy specific properties from one object to another new object

Javascript - Deep copy specific properties from one object to another new object


By : praneet
Date : March 29 2020, 07:55 AM
seems to work fine This should do what you are looking for, including circular references.
EDIT: keep in mind this will get slower and slower for objects with lots of circular references inside! The lookup to see if a reference has been seen is a simple scan.
code :
var util = require('util')


var propertiesToCopy = {
    'a' : true,
    'b' : true,
    'c' : true,
    'd' : true,
    'e' : true,
    'f' : true,
    'p1': true,
    'p2': true,
    'g' : true
};

var obj;

obj = {
    p2 : { 
        a : 1,
        b : 2,
        c : {},
        d : {
            f : 2
        }
    },
    p3 : 'hello'
};

// circular
obj.p1 = obj;
obj.p2.d.e = obj;

// sub-circular
obj.p2.g = obj.p2.c;

function getNewObjectFromObjects(obj, objects) {
    for (var i = 0; i < objects.length; i++) {
        if (obj === objects[i].old) return  objects[i].new;
    }
    return false;
}

function whiteListedCopy(obj, whitelist, root, newRoot, objects) {
    var cloned = {};
    var keys = Object.keys(obj);
    root = root || obj;
    newRoot = newRoot || cloned;
    objects = objects || [ {'old' : root, 'new': newRoot} ];
    keys.forEach(function(val) {
        if (whitelist[val] === true) {
            if (typeof(obj[val]) === typeof({}) || 
                typeof(obj[val]) === typeof([]) ) {
                var reference = getNewObjectFromObjects(obj[val], objects);
                if (reference === false) {
                cloned[val] = whiteListedCopy(obj[val], whitelist, root, newRoot, objects);                                         
                    objects.push({ 'old' : obj[val], 'new': cloned[val]});
                } else {
                    cloned[val] = reference;
                }
            } else {
                cloned[val] = obj[val];
            }
        }
    });
    return cloned;
}

var clonedObject = whiteListedCopy(obj, propertiesToCopy);

console.log(util.inspect(clonedObject));

console.log('assert c and g are same reference:', clonedObject.p2.g === clonedObject.p2.c);
console.log('assert p1 is circular:', clonedObject === clonedObject.p1);
Deep-copy Object with Array of Object Properties - how to or alternative?

Deep-copy Object with Array of Object Properties - how to or alternative?


By : RahulZ
Date : March 29 2020, 07:55 AM
To fix this issue You could extend the approach from this question, and implement a custom __clone method for each of your classes. Since there don't seem to be any relations between the nodes or edges themselves, it should be enough to accomplish what you want.
It might be worth mentioning that, as described in the documentation, __clone is invoked on the new object just after cloning. It isn't actually responsible for cloning the object which might seem logical at first.
code :
class Tree
{
    private $nodes;

    private $edges;

    public function __clone()
    {
        $this->nodes = array_map(function ($node) {
            return clone $node;
        }, $this->nodes);

        $this->edges = array_map(function ($edge) {
            return clone $edge;
        }, $this->edges);

        // clone other properties as necessary
    }
}

class Node
{
    private $values;

    private $someArray;

    public function __clone()
    {
        $this->values = array_map(function ($value) {
            return clone $value;
        }, $this->values);

        $this->someArray = array_map(function ($elem) {
            return clone $elem;
        }, $this->someArray);

        // clone other properties as necessary
    }
}
Related Posts Related Posts :
  • How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph
  • How to run a .NET Core console application on Linux
  • UI not updating for bound element
  • C# Odata v4 open type raw values
  • DocumentFormat.OpenXml Modify Creator Propery of Document
  • How to SetBasePath in ConfigurationBuilder in Core 2.0
  • ASP MVC5 public readonly variable changes value when it should not
  • How to conditionally select item from hashset with queryable linq?
  • Progress Bar C# not showing the real progress
  • Correct logic to reconnect in SignalR with HubConnection
  • ComboBox with two or more sections
  • .NET listbox to SQLite DB
  • C# Ninject binding from Dictionary<Type, Type>
  • asp.net mvc -view displaying real-time progress status
  • Getting reference to dependent in service with generic type
  • Implementing EqualityCompare vs overriding GetHashCode and Equals
  • C# Linq Find all indexes of item in List<int> within another List<int>
  • XML image how to display at data grid columns in c#.net
  • How to override Equals and GetHash of HashSet
  • Creating Windows authentication and SQL Server authentication in login form
  • How to interop with Azure Service Bus topics created by MassTransit using Rebus?
  • MVC 5 Google Calendar Integration
  • C# - Use parallel arrays to calculate cost of a phone call in GUI
  • Use a int in entire code
  • How to display newly added element at the top of StackPanel in WPF?
  • T4MVC is generating T4MVC.cs and T4MVC1.cs
  • Remove blur effect on certain controls inside UserControl
  • Sql Transcation Query to Linq Query in Wcf Rest Service
  • Setting AWS S3 credentials in C# app
  • does not contain in an ObservableCollection
  • App doesn't run it crashed directly after I started it
  • Is it possible in Entity Framework MVC application to run .sql scripts on a different database
  • Type Inference with Deconstruct tuple assignment extension methods
  • Setting up mock objects for EF dbcontext to test repository methods
  • Using C# in XSLT with MSXSL 6.0
  • Absolute positioning of UIElement in FlowDocument in WPF
  • Display debuggers not showing up in Visual Studio 2017
  • Discord.NET Users playing the same game
  • Azure function output API call to 3rd party service
  • Unable to determine the relationship represented by navigation property ASP.NET core 2.0 Entity Framework
  • Regex to find group of Regex inside a word
  • When calling a method, when to reference the class, and when to reference the object?
  • AmazonCloudWatchLogsClient async methods failing with no error
  • Create FileStream in memory instead of saving a physical file on disk
  • ViewBag data coming from ActionFilter is persisting in session even after database
  • ERROR: the name 'lvSubCategories' does not exist in the current context
  • Why datetime can't recognise the string?
  • Getting 500 error while requesting to webservice using Ajax AutoCompleteExtender
  • The property 'x' is not a navigation property of entity type 'y'
  • ASP.NET MVC - How to generate empty input boxes in loop when model is empty?
  • Need help writing regular expression
  • Add/remove buttons to a panel with an arraylist c#
  • Linq .Where(type = typeof(xxx)) comparison is always false
  • Using EF6 Code First without migrations to an existing db how do I specify column names of the many to many join table?
  • C# - Using Thread.Sleep precisely in a console application
  • Add item to a List<Tuple> inside another list
  • Double[,], inversion C#
  • Counting a string to ensure the input is within a min/max boundary
  • Assign invalidValue to Enum variable (why is this not throwing an Exception?)
  • Namespace or type specified in the project-level Imports 'System.Threading.Tasks' doesn't contain any public member or c
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org